<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="Python,编程语言入门">
    <meta name="description" content="C# | Web | html | python |">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
	<meta name="baidu-site-verification" content="code-c9IEbSDR1U" />

	
    <!-- Global site tag (gtag.js) - Google Analytics -->


    <title>Python入门 | X-Y-Z`s Blog</title>
	
    <link rel="icon" type="image/png" href="/favicon.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">

    <script src="/libs/jquery/jquery.min.js"></script>
    <script src="https://sdk.jinrishici.com/v2/browser/jinrishici.js" charset="utf-8"></script>
<meta name="generator" content="Hexo 5.4.0">
<style>.github-emoji { position: relative; display: inline-block; width: 1.2em; min-height: 1.2em; overflow: hidden; vertical-align: top; color: transparent; }  .github-emoji > span { position: relative; z-index: 10; }  .github-emoji img, .github-emoji .fancybox { margin: 0 !important; padding: 0 !important; border: none !important; outline: none !important; text-decoration: none !important; user-select: none !important; cursor: auto !important; }  .github-emoji img { height: 1.2em !important; width: 1.2em !important; position: absolute !important; left: 50% !important; top: 50% !important; transform: translate(-50%, -50%) !important; user-select: none !important; cursor: auto !important; } .github-emoji-fallback { color: inherit; } .github-emoji-fallback img { opacity: 0 !important; }</style>
<link rel="stylesheet" href="/css/prism-tomorrow.css" type="text/css"></head>



   <style>
    body{
       background-image: url(/medias/background.JPG);
       background-repeat:no-repeat;
       background-size:cover;
       background-attachment:fixed;
    }
</style>



<body  onload="opener.location.reload()">

	
    <header class="navbar-fixed">

<script>
var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?b3593488200a34a873defcaa11fc888a";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script>


    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">X-Y-Z`s Blog</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>标签</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="" class="waves-effect waves-light">

      
      <i class="fas fa-sitemap" style="zoom: 0.6;"></i>
      
      <span>归类</span>
      <i class="fas fa-chevron-down" aria-hidden="true" style="zoom: 0.6;"></i>
    </a>
    <ul class="sub-nav menus_item_child ">
      
      <li>
        <a href="/categories">
          
          <i class="fas fa-bookmark" style="margin-top: -20px; zoom: 0.6;"></i>
          
          <span>分类</span>
        </a>
      </li>
      
      <li>
        <a href="/archives">
          
          <i class="fas fa-archive" style="margin-top: -20px; zoom: 0.6;"></i>
          
          <span>归档</span>
        </a>
      </li>
      
    </ul>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/navigate" class="waves-effect waves-light">
      
      <i class="fas fa-location-arrow" style="zoom: 0.6;"></i>
      
      <span>导航</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/contact" class="waves-effect waves-light">
      
      <i class="fas fa-comments" style="zoom: 0.6;"></i>
      
      <span>留言</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/friends" class="waves-effect waves-light">
      
      <i class="fas fa-address-book" style="zoom: 0.6;"></i>
      
      <span>友链</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>


<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">X-Y-Z`s Blog</div>
        <div class="logo-desc">
            
            C# | Web | html | python |
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			标签
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="javascript:;">
			
				<i class="fa-fw fas fa-sitemap"></i>
			
			归类
			<span class="m-icon"><i class="fas fa-chevron-right"></i></span>
		</a>
            <ul  style="background:  ;" >
              
                <li>

                  <a href="/categories " style="margin-left:50px">
				  
				   <i class="fa fas fa-bookmark" style="position: absolute;left:28px" ></i>
			      
		          <span>分类</span>
                  </a>
                </li>
              
                <li>

                  <a href="/archives " style="margin-left:50px">
				  
				   <i class="fa fas fa-archive" style="position: absolute;left:28px" ></i>
			      
		          <span>归档</span>
                  </a>
                </li>
              
            </ul>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/navigate" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-location-arrow"></i>
			
			Navigate
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			关于
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/contact" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-comments"></i>
			
			留言板
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/friends" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-address-book"></i>
			
			友情链接
		</a>
          
        </li>
        
        
        <li><div class="divider"></div></li>
        <li>
            <a href="https://github.com/blinkfox/hexo-theme-matery" class="waves-effect waves-light" target="_blank">
                <i class="fab fa-github-square fa-fw"></i>Fork He
            </a>
        </li>
        
    </ul>
</div>


        </div>

        
            <style>
    .nav-transparent .github-corner {
        display: none !important;
    }

    .github-corner {
        position: absolute;
        z-index: 10;
        top: 0;
        right: 0;
        border: 0;
        transform: scale(1.1);
    }

    .github-corner svg {
        color: #4e9ef5;
        fill: #fff;
        height: 64px;
        width: 64px;
    }

    .github-corner:hover .octo-arm {
        animation: a 0.56s ease-in-out;
    }

    .github-corner .octo-arm {
        animation: none;
    }

    @keyframes a {
        0%,
        to {
            transform: rotate(0);
        }
        20%,
        60% {
            transform: rotate(-25deg);
        }
        40%,
        80% {
            transform: rotate(10deg);
        }
    }
</style>

<a href="https://github.com/blinkfox/hexo-theme-matery" class="github-corner tooltipped hide-on-med-and-down" target="_blank"
   data-tooltip="Fork He" data-position="left" data-delay="50">
    <svg viewBox="0 0 250 250" aria-hidden="true">
        <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
        <path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2"
              fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path>
        <path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z"
              fill="currentColor" class="octo-body"></path>
    </svg>
</a>
        
    </nav>

</header>

    



<div class="bg-cover pd-header post-cover" style="background-image: url('/medias/featureimages/19.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">Python入门</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        width: 345px;
        padding-left: 20px;
    }

	.toc-widget.card.toc-fixed {
    opacity: 0.85;
	}
    .toc-widget .toc-title {
        padding: 35px 0 15px 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content {
        padding-bottom: 30px;
		height: 500px;
		overflow: auto;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }
    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;

        position: absolute;
        right: 23.5vw;
        display: block;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/Python/">
                                <span class="chip bg-color">Python</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/Python/" class="post-category">
                                Python
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2021-08-21
                </div>
                

                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-check fa-fw"></i>更新日期:&nbsp;&nbsp;
                    2022-02-23
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-file-word fa-fw"></i>文章字数:&nbsp;&nbsp;
                    10.7k
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-clock fa-fw"></i>阅读时长:&nbsp;&nbsp;
                    46 分
                </div>
                

                
            </div>
        </div>
        <hr class="clearfix">

        

        
        <!-- 代码块折行 -->
        <style type="text/css">
            code[class*="language-"], pre[class*="language-"] { white-space: pre-wrap !important; }
        </style>
        

        <div class="card-content article-card-content">
            <div id="articleContent">
                <h2 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h2><p>假期自学，代码都是自己看视频时联想敲得，与任何教程无关。为了腾电脑的地方，顺便复习下，学习后边的内容，就整理了下之前敲得。注释与解释不太多（别幻想别人写一大堆注释，有写注释的习惯吗），看的话凑活看，不懂得可以联系me。其他内容持续更新。</p>
<p>python版本:3.6.6</p>
<p>python在线运行代码：-&gt;&gt;&gt;&gt; [菜鸟在线 Editor](<a target="_blank" rel="noopener" href="https://www.runoob.com/try/runcode.php?filename=HelloWorld&amp;type=python3">菜鸟教程在线编辑器 (runoob.com)</a>)-&gt;&gt;&gt;&gt;</p>
<h2 id="基本输入输出"><a href="#基本输入输出" class="headerlink" title="基本输入输出"></a>基本输入输出</h2><p>输入  input(string)。string 为提示的语句。</p>
<p>输出  print(value)。括号内可以是任意变量名，或者值。</p>
<p>功能很多，后边还有。</p>
<h2 id="1-if…elif…else"><a href="#1-if…elif…else" class="headerlink" title="1. if…elif…else"></a>1. if…elif…else</h2><ul>
<li><p>if条件中 且 用‘and’ 或 用‘or’</p>
</li>
<li><p> keyword: “产生随机字符串”，</p>
</li>
</ul>
 <figure class="highlight python"><table><tbody><tr><td class="code"><pre class=" language-hljs python"> <span class="hljs-comment">##  if条件中 且 用‘and’ 或 用‘or’</span><br>  <br>n = <span class="hljs-built_in">input</span>(<span class="hljs-string">"输入任意数字"</span>)<br><span class="hljs-keyword">if</span> <span class="hljs-built_in">int</span>(n) % <span class="hljs-number">2</span> == <span class="hljs-number">0</span> <span class="hljs-keyword">and</span> n != <span class="hljs-string">"0"</span>:<br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">"输入为偶数"</span>)<br><span class="hljs-keyword">elif</span> <span class="hljs-built_in">int</span>(n) % <span class="hljs-number">2</span> != <span class="hljs-number">0</span>:<br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">"输入为奇数"</span>)<br><span class="hljs-keyword">else</span>:<br>    <span class="hljs-built_in">print</span>(<span class="hljs-string"><code class="language-hljs python"> <span class="hljs-comment">##  if条件中 且 用‘and’ 或 用‘or’</span><br>  <br>n = <span class="hljs-built_in">input</span>(<span class="hljs-string">"输入任意数字"</span>)<br><span class="hljs-keyword">if</span> <span class="hljs-built_in">int</span>(n) % <span class="hljs-number">2</span> == <span class="hljs-number">0</span> <span class="hljs-keyword">and</span> n != <span class="hljs-string">"0"</span>:<br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">"输入为偶数"</span>)<br><span class="hljs-keyword">elif</span> <span class="hljs-built_in">int</span>(n) % <span class="hljs-number">2</span> != <span class="hljs-number">0</span>:<br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">"输入为奇数"</span>)<br><span class="hljs-keyword">else</span>:<br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">"输入非数字或 “0” "</span>)<br>  <br></code></pre></td></tr></tbody></table></figure>

<h2 id="2-运算符、文件写入、id"><a href="#2-运算符、文件写入、id" class="headerlink" title="2. 运算符、文件写入、id()"></a>2. 运算符、文件写入、id()</h2><h3 id="2-1运算符"><a href="#2-1运算符" class="headerlink" title="2.1运算符"></a>2.1运算符</h3><h4 id="2-1-1-算数与赋值运算符"><a href="#2-1-1-算数与赋值运算符" class="headerlink" title="2.1.1 算数与赋值运算符"></a>2.1.1 算数与赋值运算符</h4><p>​    几个与其他语言不同，或比较特殊的几个。</p>
<p>​      ** ：幂，如2**5为2^5^ 。</p>
<p>​      //  ：取整除，“/”，所得结果带小数部分。“//”，结果只有整数部分。</p>
<p>​      /=、//=、**=：类比理解。</p>
<h3 id="2-1-2-逻辑运算符"><a href="#2-1-2-逻辑运算符" class="headerlink" title="2.1.2 逻辑运算符"></a>2.1.2 逻辑运算符</h3><p>​    在条件组合时不是其他语言那样  “||”, “&amp;&amp;”,  “!”。</p>
<ul>
<li>“||” 用 “or” 替换</li>
<li>“&amp;&amp;” 用 “and” 替换</li>
<li>“!” 用 “not” 替换</li>
</ul>
<h3 id="2-1-3-位运算符"><a href="#2-1-3-位运算符" class="headerlink" title="2.1.3 位运算符"></a>2.1.3 位运算符</h3><p>​    &amp; <sup>与</sup> ， | <sup>或</sup>， ^ <sup>异或</sup> ， ~ <sup>取反</sup>， &lt;&lt; <sup>左移</sup>， &gt;&gt; <sup>右移</sup>。运算只针对于二进制数，运算逻辑与其他语言相同。</p>
<p>其中用到  <mark>格式化输出字符串</mark> 。可通过目录前往了解学习。</p>
<figure class="highlight python"><table><tbody><tr><td class="code"><pre class=" language-hljs python"><span class="hljs-comment">#  encoding:utf-8</span><br><span class="hljs-comment">#  keyword:“input”，“逻辑运算符”，“&gt;&gt;”，“&lt;&lt;”，“|”，“^”,</span><br><span class="hljs-comment">#      “变量地址”</span><br><span class="hljs-keyword">from</span> os <span class="hljs-keyword">import</span> error<br><br>a = <span class="hljs-built_in">input</span>(<span class="hljs-string">"输入字符串"</span>)<br>x = <span class="hljs-built_in">input</span>(<span class="hljs-string">"输入一个数 X:"</span>)<br><br><span class="hljs-comment"># 输入x</span><br><span class="hljs-keyword">try</span>:<br>    x = <span class="hljs-built_in">int</span>(x)<br><span class="hljs-keyword">except</span>:<br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">"输入数据有误!"</span>)<br>    exit(<span class="hljs-number">0</span>)<br><span class="hljs-comment"># 输入y</span><br>y = <span class="hljs-built_in">input</span>(<span class="hljs-string">"输入一个数Y:"</span>)<br><span class="hljs-keyword">try</span>:<br>    y = <span class="hljs-built_in">int</span>(y)<br><span class="hljs-keyword">except</span>:<br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">"输入数据有误!"</span>)<br>    exit(<span class="hljs-number">0</span>)<br><br>templea = <span class="hljs-string">"% 8s\n% 10d\n"</span><br>templeb = <span class="hljs-string">"{0: &gt;9s}\n{1: &gt;#20b}\n"</span><br>templec = <span class="hljs-string">"{0: &gt;9s}\n{1: &gt;#20b}\n{2: &gt;#20b}\n"</span><br><br>a += <span class="hljs-string">"\n"</span><br>prs1 = [<br>    (<span class="hljs-string">"原数(x):"</span>, x),<br>    (<span class="hljs-string">"原数(y):"</span>, y),<br>    (<span class="hljs-string">"值id(x)："</span>, <span class="hljs-built_in">id</span>(x)),<br>]<br>prs2 = [<br>    (<span class="hljs-string">"二进制(x):"</span>, x),<br>    (<span class="hljs-string">"二进制(y):"</span>, y),<br>    (<span class="hljs-string">"右，移(x&gt;&gt;2):"</span>, x &gt;&gt; <span class="hljs-number">2</span>),<br>    (<span class="hljs-string">"左，移(x&lt;&lt;2):"</span>, x &lt;&lt; <span class="hljs-number">2</span>),<br>]<br>prs3 = [<br>    (<span class="hljs-string">"异或(x^y,y^x):"</span>, x ^ y, y ^ x),<br>    (<span class="hljs-string">"_或(x|y，y|x):"</span>, x | y, y | x),<br>]<br><span class="hljs-keyword">for</span> item <span class="hljs-keyword">in</span> prs1:<br>    a += templea % item<br><span class="hljs-keyword">for</span> item <span class="hljs-keyword">in</span> prs2:<br>    a += templeb.<span class="hljs-built_in">format</span>(item[<span class="hljs-number">0</span>], item[<span class="hljs-number">1</span>])<br><span class="hljs-keyword">for</span> item <span class="hljs-keyword">in</span> prs3:<br>    a += templec.<span class="hljs-built_in">format</span>(item[<span class="hljs-number">0</span>], item[<span class="hljs-number">1</span>], item[<span class="hljs-number"><code class="language-hljs python"><span class="hljs-comment">#  encoding:utf-8</span><br><span class="hljs-comment">#  keyword:“input”，“逻辑运算符”，“&gt;&gt;”，“&lt;&lt;”，“|”，“^”,</span><br><span class="hljs-comment">#      “变量地址”</span><br><span class="hljs-keyword">from</span> os <span class="hljs-keyword">import</span> error<br><br>a = <span class="hljs-built_in">input</span>(<span class="hljs-string">"输入字符串"</span>)<br>x = <span class="hljs-built_in">input</span>(<span class="hljs-string">"输入一个数 X:"</span>)<br><br><span class="hljs-comment"># 输入x</span><br><span class="hljs-keyword">try</span>:<br>    x = <span class="hljs-built_in">int</span>(x)<br><span class="hljs-keyword">except</span>:<br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">"输入数据有误!"</span>)<br>    exit(<span class="hljs-number">0</span>)<br><span class="hljs-comment"># 输入y</span><br>y = <span class="hljs-built_in">input</span>(<span class="hljs-string">"输入一个数Y:"</span>)<br><span class="hljs-keyword">try</span>:<br>    y = <span class="hljs-built_in">int</span>(y)<br><span class="hljs-keyword">except</span>:<br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">"输入数据有误!"</span>)<br>    exit(<span class="hljs-number">0</span>)<br><br>templea = <span class="hljs-string">"% 8s\n% 10d\n"</span><br>templeb = <span class="hljs-string">"{0: &gt;9s}\n{1: &gt;#20b}\n"</span><br>templec = <span class="hljs-string">"{0: &gt;9s}\n{1: &gt;#20b}\n{2: &gt;#20b}\n"</span><br><br>a += <span class="hljs-string">"\n"</span><br>prs1 = [<br>    (<span class="hljs-string">"原数(x):"</span>, x),<br>    (<span class="hljs-string">"原数(y):"</span>, y),<br>    (<span class="hljs-string">"值id(x)："</span>, <span class="hljs-built_in">id</span>(x)),<br>]<br>prs2 = [<br>    (<span class="hljs-string">"二进制(x):"</span>, x),<br>    (<span class="hljs-string">"二进制(y):"</span>, y),<br>    (<span class="hljs-string">"右，移(x&gt;&gt;2):"</span>, x &gt;&gt; <span class="hljs-number">2</span>),<br>    (<span class="hljs-string">"左，移(x&lt;&lt;2):"</span>, x &lt;&lt; <span class="hljs-number">2</span>),<br>]<br>prs3 = [<br>    (<span class="hljs-string">"异或(x^y,y^x):"</span>, x ^ y, y ^ x),<br>    (<span class="hljs-string">"_或(x|y，y|x):"</span>, x | y, y | x),<br>]<br><span class="hljs-keyword">for</span> item <span class="hljs-keyword">in</span> prs1:<br>    a += templea % item<br><span class="hljs-keyword">for</span> item <span class="hljs-keyword">in</span> prs2:<br>    a += templeb.<span class="hljs-built_in">format</span>(item[<span class="hljs-number">0</span>], item[<span class="hljs-number">1</span>])<br><span class="hljs-keyword">for</span> item <span class="hljs-keyword">in</span> prs3:<br>    a += templec.<span class="hljs-built_in">format</span>(item[<span class="hljs-number">0</span>], item[<span class="hljs-number">1</span>], item[<span class="hljs-number">2</span>])<br></code></pre></td></tr></tbody></table></figure>



<h2 id="3-while"><a href="#3-while" class="headerlink" title="3. while"></a>3. while</h2><p>与其他语言没大区别，就是没括号</p>
<figure class="highlight python"><table><tbody><tr><td class="code"><pre class=" language-hljs python">string = <span class="hljs-string">"A"</span><br><span class="hljs-comment">#  根据字符取ascll码值</span><br>a = <span class="hljs-built_in">ord</span>(<span class="hljs-string">"A"</span>)<br>i = <span class="hljs-number">0</span><br><span class="hljs-keyword">while</span> i &lt; <span class="hljs-number">60</span>:<br>  <span class="hljs-comment">#  根据ascll码值取字符</span><br>  st ring += <span class="hljs-built_in">chr</span>(a)<br>  <span class="hljs-keyword">if</span> i % <span class="hljs-number">3</span> == <span class="hljs-number">0</span>:<br>	 <span class="hljs-built_in">print</span>()<br>  <span class="hljs-built_in">print</span>(a, <span class="hljs-string">":"</span> + <span class="hljs-built_in">chr</span>(a), end=<span class="hljs-string">" "</span>)<br>  i = i + <span class="hljs-number">1</span><br>  a = a + <span class="hljs-number">1</span><br><span class="hljs-built_in"><code class="language-hljs python">string = <span class="hljs-string">"A"</span><br><span class="hljs-comment">#  根据字符取ascll码值</span><br>a = <span class="hljs-built_in">ord</span>(<span class="hljs-string">"A"</span>)<br>i = <span class="hljs-number">0</span><br><span class="hljs-keyword">while</span> i &lt; <span class="hljs-number">60</span>:<br>  <span class="hljs-comment">#  根据ascll码值取字符</span><br>  st ring += <span class="hljs-built_in">chr</span>(a)<br>  <span class="hljs-keyword">if</span> i % <span class="hljs-number">3</span> == <span class="hljs-number">0</span>:<br>	 <span class="hljs-built_in">print</span>()<br>  <span class="hljs-built_in">print</span>(a, <span class="hljs-string">":"</span> + <span class="hljs-built_in">chr</span>(a), end=<span class="hljs-string">" "</span>)<br>  i = i + <span class="hljs-number">1</span><br>  a = a + <span class="hljs-number">1</span><br><span class="hljs-built_in">print</span>(string)<br></code></pre></td></tr></tbody></table></figure>

<h2 id="4-序列"><a href="#4-序列" class="headerlink" title="4. 序列"></a>4. 序列</h2><p>连续内存空间数据存储，每个项都有唯一值（成为索引或位置）指向。</p>
<p>序列结构有：</p>
<ul>
<li><p>列表 [ list,list,list ]。</p>
</li>
<li><p>元组 (tuple, tuple, tuple)。</p>
</li>
<li><p>字典 { dictionary, dictionary, dictionary }。</p>
</li>
<li><p>字符串 string</p>
<blockquote>
<p>​        定义时：序列为  [ ] ,元组为 ( ) ,字典为 { } 。每项都可以是其他数据结构，即各项之间没有必要的限制条件。</p>
</blockquote>
</li>
</ul>
<h3 id="4-1-列表"><a href="#4-1-列表" class="headerlink" title="4.1 列表"></a>4.1 列表</h3><ul>
<li><p>通过确定值初始化。</p>
<figure class="highlight python"><table><tbody><tr><td class="code"><pre class=" language-hljs python"><code class="language-hljs python">listname =[ value1,value2 ,value3 ,value4 ,value5 ,value6]<br></code></pre></td></tr></tbody></table></figure></li>
<li><p>通过表达式初始化。</p>
<ol>
<li><p>生成指定范围列表。</p>
<p>使用range函数控制生成元素数量，<code>listname =[expression for var in range]</code></p>
<ul>
<li><p>expression 。当前生成元素var进行的运算。</p>
<blockquote>
<p><code>do0</code>  或</p>
<p><code>do1 if case1 else if do2 else do3</code></p>
</blockquote>
</li>
<li><p>var 。当前生成元素的变量名。</p>
</li>
<li><p>range 。 range函数指定生成数量。</p>
</li>
</ul>
<figure class="highlight python"><table><tbody><tr><td class="code"><pre class=" language-hljs python">listname=[i+<span class="hljs-number">0.1</span> <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(<span class="hljs-number"><code class="language-hljs python">listname=[i+<span class="hljs-number">0.1</span> <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(<span class="hljs-number">20</span>)]<br></code></pre></td></tr></tbody></table></figure></li>
<li><p>根据列表生成列表。</p>
<p>就是在 1 的基础上用一个列表替换了range函数。</p>
<figure class="highlight python"><table><tbody><tr><td class="code"><pre class=" language-hljs python">listname=[i <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(<span class="hljs-number">10</span>)] <span class="hljs-comment">#先 生成一个列表</span><br>newList=[ i%<span class="hljs-number">5</span>+<span class="hljs-number">1</span> <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> listname]<span class="hljs-comment"><code class="language-hljs python">listname=[i <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(<span class="hljs-number">10</span>)] <span class="hljs-comment">#先 生成一个列表</span><br>newList=[ i%<span class="hljs-number">5</span>+<span class="hljs-number">1</span> <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> listname]<span class="hljs-comment"># 根据那个生成这个。全部变为1~5</span><br></code></pre></td></tr></tbody></table></figure></li>
<li><p>添加筛选条件。 </p>
<figure class="highlight python"><table><tbody><tr><td class="code"><pre class=" language-hljs python">listname=[i <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(<span class="hljs-number">20</span>)] <span class="hljs-comment">#再 生成一个列表</span><br>newList=[ i <span class="hljs-keyword">if</span> i%<span class="hljs-number">2</span>==<span class="hljs-number">0</span> <span class="hljs-keyword">else</span> i*<span class="hljs-number">10</span> <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> <span class="hljs-built_in">list</span> <span class="hljs-keyword">if</span> i &lt;<span class="hljs-number">10</span>]<br><span class="hljs-comment"><code class="language-hljs python">listname=[i <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(<span class="hljs-number">20</span>)] <span class="hljs-comment">#再 生成一个列表</span><br>newList=[ i <span class="hljs-keyword">if</span> i%<span class="hljs-number">2</span>==<span class="hljs-number">0</span> <span class="hljs-keyword">else</span> i*<span class="hljs-number">10</span> <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> <span class="hljs-built_in">list</span> <span class="hljs-keyword">if</span> i &lt;<span class="hljs-number">10</span>]<br><span class="hljs-comment"># 根据那个 添加筛选条件并生成新的。首先判断是否小于10，然后再看前边的条件怎么进行运算。</span><br></code></pre></td></tr></tbody></table></figure></li>
</ol>
<p>以上几种操作，等同于</p>
<figure class="highlight python"><table><tbody><tr><td class="code"><pre class=" language-hljs python"><span class="hljs-built_in">list</span>=[]<br><span class="hljs-keyword">for</span> item <span class="hljs-keyword">in</span> <span class="hljs-built_in">list</span>:<br>	<span class="hljs-keyword">if</span>  item... :<br>        <span class="hljs-comment">#执行操作</span><br>    <span class="hljs-keyword">elif</span> item... :<br>        <span class="hljs-comment">#执行操作</span><br>    <span class="hljs-keyword">else</span>:<br>        <span class="hljs-comment"><code class="language-hljs python"><span class="hljs-built_in">list</span>=[]<br><span class="hljs-keyword">for</span> item <span class="hljs-keyword">in</span> <span class="hljs-built_in">list</span>:<br>	<span class="hljs-keyword">if</span>  item... :<br>        <span class="hljs-comment">#执行操作</span><br>    <span class="hljs-keyword">elif</span> item... :<br>        <span class="hljs-comment">#执行操作</span><br>    <span class="hljs-keyword">else</span>:<br>        <span class="hljs-comment">#执行操作</span><br></code></pre></td></tr></tbody></table></figure></li>
</ul>
<h4 id="4-1-1-列表的基本操作"><a href="#4-1-1-列表的基本操作" class="headerlink" title="4.1.1 列表的基本操作"></a>4.1.1 列表的基本操作</h4><ul>
<li><p>索引（Indexing）。列表可通过索引取值，与其他编程语言数组操作一样。</p>
<ul>
<li><p><code>listname.index ( value )</code>。返回指定值第一次出现的索引值。</p>
<blockquote>
<p>指定值不存在会报错，所以建议结合 in 操作。（在4.1.2）</p>
</blockquote>
</li>
</ul>
</li>
<li><blockquote>
<p><mark>序列支持负数索引</mark>, 当索引值为负时从右向左数</p>
</blockquote>
</li>
<li><p>切片（Slicing）。取出整个序列的连续一部分。</p>
<blockquote>
<p>list ( start , end,step)</p>
</blockquote>
<figure class="highlight python"><table><tbody><tr><td class="code"><pre class=" language-hljs python">name = [<span class="hljs-string">"张三"</span>, <span class="hljs-string">"张四"</span>, <span class="hljs-string">"张五"</span>, <span class="hljs-string">"李四"</span>, <span class="hljs-string">"李五"</span>]<br>number = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]<br><br>namenum = name + number<br><br><span class="hljs-built_in">print</span>(<span class="hljs-string">"namenum[1:5:2]"</span>, namenum[<span class="hljs-number">1</span>:<span class="hljs-number">5</span>:<span class="hljs-number">2</span>], <span class="hljs-string">""</span>)<br><span class="hljs-comment"># 切片[ 从第 2 个开始，到第 6 个以前，间隔为 2 ]</span><br><span class="hljs-built_in">print</span>(<span class="hljs-string">"namenum[:5:]"</span>, namenum[:<span class="hljs-number">5</span>:], <span class="hljs-string"><code class="language-hljs python">name = [<span class="hljs-string">"张三"</span>, <span class="hljs-string">"张四"</span>, <span class="hljs-string">"张五"</span>, <span class="hljs-string">"李四"</span>, <span class="hljs-string">"李五"</span>]<br>number = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]<br><br>namenum = name + number<br><br><span class="hljs-built_in">print</span>(<span class="hljs-string">"namenum[1:5:2]"</span>, namenum[<span class="hljs-number">1</span>:<span class="hljs-number">5</span>:<span class="hljs-number">2</span>], <span class="hljs-string">""</span>)<br><span class="hljs-comment"># 切片[ 从第 2 个开始，到第 6 个以前，间隔为 2 ]</span><br><span class="hljs-built_in">print</span>(<span class="hljs-string">"namenum[:5:]"</span>, namenum[:<span class="hljs-number">5</span>:], <span class="hljs-string">""</span>)<br></code></pre></td></tr></tbody></table></figure></li>
<li><p>加（Adding）。两个序列所有元素直接相加。</p>
</li>
<li><p>乘（Multiplying）。序列 乘一个整数，产生一个同样的序列重复整数次的新序列。  </p>
<figure class="highlight python"><table><tbody><tr><td class="code"><pre class=" language-hljs python"><span class="hljs-built_in">print</span>(<span class="hljs-string">""</span>)<br>name=[<span class="hljs-string">"张三"</span>,<span class="hljs-string">"张四"</span>,<span class="hljs-string">"张五"</span>,<span class="hljs-string">"李四"</span>,<span class="hljs-string">"李五"</span>]<br>number=[<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>]<br><span class="hljs-comment">#  乘</span><br><span class="hljs-built_in">print</span>(name*<span class="hljs-number">3</span>)<br><span class="hljs-comment">#  加</span><br><span class="hljs-built_in">print</span>(<span class="hljs-string">"name+number"</span>, name+number,<span class="hljs-string">""</span>)<br><span class="hljs-comment">#  切片【从第二个开始，到第六个以前，间隔为2】</span><br>namenum=name+number<br><span class="hljs-built_in">print</span>(<span class="hljs-string">"namenum[1:5:2]"</span>,namenum[<span class="hljs-number">1</span>:<span class="hljs-number">5</span>:<span class="hljs-number">2</span>],<span class="hljs-string">""</span>)<br><span class="hljs-built_in">print</span>(<span class="hljs-string">"namenum[:5:]"</span>,namenum[:<span class="hljs-number">5</span>:],<span class="hljs-string"><code class="language-hljs python"><span class="hljs-built_in">print</span>(<span class="hljs-string">""</span>)<br>name=[<span class="hljs-string">"张三"</span>,<span class="hljs-string">"张四"</span>,<span class="hljs-string">"张五"</span>,<span class="hljs-string">"李四"</span>,<span class="hljs-string">"李五"</span>]<br>number=[<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>]<br><span class="hljs-comment">#  乘</span><br><span class="hljs-built_in">print</span>(name*<span class="hljs-number">3</span>)<br><span class="hljs-comment">#  加</span><br><span class="hljs-built_in">print</span>(<span class="hljs-string">"name+number"</span>, name+number,<span class="hljs-string">""</span>)<br><span class="hljs-comment">#  切片【从第二个开始，到第六个以前，间隔为2】</span><br>namenum=name+number<br><span class="hljs-built_in">print</span>(<span class="hljs-string">"namenum[1:5:2]"</span>,namenum[<span class="hljs-number">1</span>:<span class="hljs-number">5</span>:<span class="hljs-number">2</span>],<span class="hljs-string">""</span>)<br><span class="hljs-built_in">print</span>(<span class="hljs-string">"namenum[:5:]"</span>,namenum[:<span class="hljs-number">5</span>:],<span class="hljs-string">""</span>)<br></code></pre></td></tr></tbody></table></figure></li>
</ul>
<h4 id="4-1-2-列表的常见方法"><a href="#4-1-2-列表的常见方法" class="headerlink" title="4.1.2 列表的常见方法"></a>4.1.2 列表的常见方法</h4><ul>
<li><p>len。 返回列表的长度。<code>len ( list )</code>。</p>
</li>
<li><p>max。输出列表中的最大值。</p>
<blockquote>
<p>只支持元素全部为数字类型的列表。<code>max ( list )</code></p>
</blockquote>
</li>
<li><p>min。用法同max。</p>
</li>
<li><p>in。返回 bool 值。<code>value in list</code>。</p>
<blockquote>
<p>只能判断一层，如果子元素为列表或者元组之类的结构，则不会判断其内部值。</p>
</blockquote>
</li>
<li><p>not in 。同上。</p>
</li>
</ul>
<figure class="highlight python"><table><tbody><tr><td class="code"><pre class=" language-hljs python">numbers=[<span class="hljs-number">1.2</span>,<span class="hljs-number">123.1</span>,<span class="hljs-number">456</span>,<span class="hljs-number">486</span>,<span class="hljs-number">456</span>,<span class="hljs-number">156</span>,<span class="hljs-number">111</span>,<span class="hljs-number">222</span>,<span class="hljs-number">333</span>]<br><span class="hljs-built_in">print</span>(numbers)<br><span class="hljs-built_in">print</span>(<span class="hljs-string">"最大值"</span>,<span class="hljs-built_in">max</span>(numbers))<br><span class="hljs-built_in">print</span>(<span class="hljs-string">"最小值"</span>,<span class="hljs-built_in">min</span>(numbers))<br><span class="hljs-built_in">print</span>(<span class="hljs-string">"长度"</span>,<span class="hljs-built_in">len</span>(numbers))<br>x=<span class="hljs-number">456</span><br><span class="hljs-built_in">print</span>(<span class="hljs-string">"是否存在"</span>,x,x <span class="hljs-keyword">in</span> numbers)<br>y=<span class="hljs-number">678</span><br><span class="hljs-built_in">print</span>(<span class="hljs-string">"是否不存在"</span>,y,y <span class="hljs-keyword">not</span> <span class="hljs-keyword"><code class="language-hljs python">numbers=[<span class="hljs-number">1.2</span>,<span class="hljs-number">123.1</span>,<span class="hljs-number">456</span>,<span class="hljs-number">486</span>,<span class="hljs-number">456</span>,<span class="hljs-number">156</span>,<span class="hljs-number">111</span>,<span class="hljs-number">222</span>,<span class="hljs-number">333</span>]<br><span class="hljs-built_in">print</span>(numbers)<br><span class="hljs-built_in">print</span>(<span class="hljs-string">"最大值"</span>,<span class="hljs-built_in">max</span>(numbers))<br><span class="hljs-built_in">print</span>(<span class="hljs-string">"最小值"</span>,<span class="hljs-built_in">min</span>(numbers))<br><span class="hljs-built_in">print</span>(<span class="hljs-string">"长度"</span>,<span class="hljs-built_in">len</span>(numbers))<br>x=<span class="hljs-number">456</span><br><span class="hljs-built_in">print</span>(<span class="hljs-string">"是否存在"</span>,x,x <span class="hljs-keyword">in</span> numbers)<br>y=<span class="hljs-number">678</span><br><span class="hljs-built_in">print</span>(<span class="hljs-string">"是否不存在"</span>,y,y <span class="hljs-keyword">not</span> <span class="hljs-keyword">in</span> numbers)<br></code></pre></td></tr></tbody></table></figure>



<h4 id="4-1-3-列表的遍历"><a href="#4-1-3-列表的遍历" class="headerlink" title="4.1.3 列表的遍历"></a>4.1.3 列表的遍历</h4><ul>
<li><p>for <b style="color:brown">item</b> in  <b style="color:brown">list</b>。 依次把list的值赋值给item，然后进行其他操作。对原列表无影响。</p>
</li>
<li><p>for <b style="color:brown">index, item</b> in <b style="color:brown">enumerate <b style="color:#E0A418">( list&nbsp;)</b></b>。</p>
<p>  ​    index为索引值，item为索引值对应的项。</p>
</li>
</ul>
<figure class="highlight python"><table><tbody><tr><td class="code"><pre class=" language-hljs python">name = [<span class="hljs-string">"dage"</span>, <span class="hljs-string">"erge"</span>, <span class="hljs-string">"sange"</span>, <span class="hljs-string">"laosi"</span>, <span class="hljs-string">"laowu"</span>, <span class="hljs-string">"xiaoliu"</span>]<br><span class="hljs-built_in">print</span>(name)<br>a=<span class="hljs-number">0</span><br><span class="hljs-keyword">for</span> linshide <span class="hljs-keyword">in</span> name:<br>  <span class="hljs-keyword">if</span> a % <span class="hljs-number">2</span>==<span class="hljs-number">0</span> :<br>    <span class="hljs-comment">## 换行</span><br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">"\n"</span>)<br>  <span class="hljs-built_in">print</span>(<span class="hljs-string">"\t"</span>+linshide,end=<span class="hljs-string">""</span>)<br>	<span class="hljs-comment">## 不换行打印</span><br>  a=a+<span class="hljs-number">1</span> <span class="hljs-comment">## python不支持自增|自减运算</span><br><span class="hljs-keyword">for</span> xuhao, name <span class="hljs-keyword">in</span> <span class="hljs-built_in">enumerate</span>(name):<br>  <span class="hljs-keyword">if</span> xuhao % <span class="hljs-number">2</span>==<span class="hljs-number">0</span> :<br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">""</span>)<br>  <span class="hljs-built_in">print</span>(<span class="hljs-string">"\t序号是："</span> + <span class="hljs-built_in">str</span>(xuhao), <span class="hljs-string">"\t名字是"</span> + name, end=<span class="hljs-string">""</span>)<span class="hljs-comment"><code class="language-hljs python">name = [<span class="hljs-string">"dage"</span>, <span class="hljs-string">"erge"</span>, <span class="hljs-string">"sange"</span>, <span class="hljs-string">"laosi"</span>, <span class="hljs-string">"laowu"</span>, <span class="hljs-string">"xiaoliu"</span>]<br><span class="hljs-built_in">print</span>(name)<br>a=<span class="hljs-number">0</span><br><span class="hljs-keyword">for</span> linshide <span class="hljs-keyword">in</span> name:<br>  <span class="hljs-keyword">if</span> a % <span class="hljs-number">2</span>==<span class="hljs-number">0</span> :<br>    <span class="hljs-comment">## 换行</span><br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">"\n"</span>)<br>  <span class="hljs-built_in">print</span>(<span class="hljs-string">"\t"</span>+linshide,end=<span class="hljs-string">""</span>)<br>	<span class="hljs-comment">## 不换行打印</span><br>  a=a+<span class="hljs-number">1</span> <span class="hljs-comment">## python不支持自增|自减运算</span><br><span class="hljs-keyword">for</span> xuhao, name <span class="hljs-keyword">in</span> <span class="hljs-built_in">enumerate</span>(name):<br>  <span class="hljs-keyword">if</span> xuhao % <span class="hljs-number">2</span>==<span class="hljs-number">0</span> :<br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">""</span>)<br>  <span class="hljs-built_in">print</span>(<span class="hljs-string">"\t序号是："</span> + <span class="hljs-built_in">str</span>(xuhao), <span class="hljs-string">"\t名字是"</span> + name, end=<span class="hljs-string">""</span>)<span class="hljs-comment">##不换行输出</span><br></code></pre></td></tr></tbody></table></figure>



<h4 id="4-1-4-列表的-增-删-改"><a href="#4-1-4-列表的-增-删-改" class="headerlink" title="4.1.4 列表的 增 删 改"></a>4.1.4 列表的 增 删 改</h4><ul>
<li><p>增，<code>apend（）</code>。</p>
</li>
<li><p>删。</p>
<ul>
<li><p><code>del listname[ index ]</code>。直接删除index索引值对应的值，后续元素前移。</p>
</li>
<li><p><code>listname.remove( “value” )</code></p>
<blockquote>
<p>删除不存在的值会报错。所以可结合 in 操作使用。</p>
</blockquote>
</li>
<li><p>listname.pop()。 删除并返回最后一个元素。</p>
<blockquote>
<p>通过与append结合使用，可以模拟栈结构。后进先出</p>
</blockquote>
</li>
</ul>
</li>
<li><p>改。 <code>listname [ index ] = value</code></p>
  <figure class="highlight python"><table><tbody><tr><td class="code"><pre class=" language-hljs python">name = [<span class="hljs-string">"dage"</span>, <span class="hljs-string">"erge"</span>, <span class="hljs-string">"sange"</span>, <span class="hljs-string">"laosi"</span>, <span class="hljs-string">"laowu"</span>, <span class="hljs-string">"xiaoliu"</span>]<br><span class="hljs-built_in">print</span>(<span class="hljs-string">"\n定义的数组为："</span>)<br><span class="hljs-built_in">print</span>(name)<br><br><span class="hljs-comment">#  添加:</span><br>name.append(<span class="hljs-string">"laomo"</span>)<br><span class="hljs-built_in">print</span>(<span class="hljs-string">"\n添加一个后的数组："</span> )<br><span class="hljs-built_in">print</span>(name)<br><br><span class="hljs-comment">#  通过索引获取指定值。直接重新赋值。</span><br>strint=name[<span class="hljs-number">0</span>]=<span class="hljs-string">"dageda"</span><br><span class="hljs-built_in">print</span>(<span class="hljs-string">"\n添加一个后再修改下的数组："</span>)<br><span class="hljs-built_in">print</span>(name)<br><br><span class="hljs-comment"># 删除指定“dage” 即 删除name[2]</span><br><span class="hljs-keyword">del</span> name[<span class="hljs-number">0</span>]<br><span class="hljs-built_in">print</span>(<span class="hljs-string">"\n删除 name[0] 的数组："</span>)<br><span class="hljs-built_in"><code class="language-hljs python">name = [<span class="hljs-string">"dage"</span>, <span class="hljs-string">"erge"</span>, <span class="hljs-string">"sange"</span>, <span class="hljs-string">"laosi"</span>, <span class="hljs-string">"laowu"</span>, <span class="hljs-string">"xiaoliu"</span>]<br><span class="hljs-built_in">print</span>(<span class="hljs-string">"\n定义的数组为："</span>)<br><span class="hljs-built_in">print</span>(name)<br><br><span class="hljs-comment">#  添加:</span><br>name.append(<span class="hljs-string">"laomo"</span>)<br><span class="hljs-built_in">print</span>(<span class="hljs-string">"\n添加一个后的数组："</span> )<br><span class="hljs-built_in">print</span>(name)<br><br><span class="hljs-comment">#  通过索引获取指定值。直接重新赋值。</span><br>strint=name[<span class="hljs-number">0</span>]=<span class="hljs-string">"dageda"</span><br><span class="hljs-built_in">print</span>(<span class="hljs-string">"\n添加一个后再修改下的数组："</span>)<br><span class="hljs-built_in">print</span>(name)<br><br><span class="hljs-comment"># 删除指定“dage” 即 删除name[2]</span><br><span class="hljs-keyword">del</span> name[<span class="hljs-number">0</span>]<br><span class="hljs-built_in">print</span>(<span class="hljs-string">"\n删除 name[0] 的数组："</span>)<br><span class="hljs-built_in">print</span>(name)<br></code></pre></td></tr></tbody></table></figure>
</li>
</ul>
<h4 id="4-1-5-列表的统计求和"><a href="#4-1-5-列表的统计求和" class="headerlink" title="4.1.5 列表的统计求和"></a>4.1.5 列表的统计求和</h4><ul>
<li><p>统计。返回指定值在列表中出现的次数。<code>list.count(value)</code></p>
<blockquote>
<p>不存在时返回 0，所以不用判断是否存在。</p>
</blockquote>
</li>
<li><p>求和。统计各项的和。可指定统计开始的位置。<code>sum( listname [ index ] )</code> 或<code>sum( listname )</code> </p>
<blockquote>
<p>仅限元素全为数字格式时。</p>
</blockquote>
  <figure class="highlight python"><table><tbody><tr><td class="code"><pre class=" language-hljs python">nums=[<span class="hljs-number">123</span>,<span class="hljs-number">456</span>,<span class="hljs-number">654</span>,<span class="hljs-number">123</span>,<span class="hljs-number">987</span>,<span class="hljs-number">147</span>,<span class="hljs-number">258</span>,<span class="hljs-number">654</span>,<span class="hljs-number">852</span>,<span class="hljs-number">147</span>,<span class="hljs-number">741</span>,<span class="hljs-number">852</span>]<br>nums_plus=nums*<span class="hljs-number">2</span><br><br><span class="hljs-comment"># 统计某一元素出现次数</span><br><span class="hljs-keyword">if</span> <span class="hljs-number">147</span> <span class="hljs-keyword">in</span> nums_plus :<br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">"147出现次数为\t:"</span>+ <span class="hljs-built_in">str</span>(nums_plus.count(<span class="hljs-number">147</span>)))<br><span class="hljs-keyword">else</span>:<br>    <span class="hljs-built_in">print</span>(<span class="hljs-built_in">str</span>(<span class="hljs-number">147</span>)+<span class="hljs-string">"不存在"</span>)<br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">"nums和:"</span>+<span class="hljs-built_in">str</span>(<span class="hljs-built_in">sum</span>(nums))+<span class="hljs-string">"\nnums_plus和为\t:"</span>+<span class="hljs-built_in">str</span>(<span class="hljs-built_in"><code class="language-hljs python">nums=[<span class="hljs-number">123</span>,<span class="hljs-number">456</span>,<span class="hljs-number">654</span>,<span class="hljs-number">123</span>,<span class="hljs-number">987</span>,<span class="hljs-number">147</span>,<span class="hljs-number">258</span>,<span class="hljs-number">654</span>,<span class="hljs-number">852</span>,<span class="hljs-number">147</span>,<span class="hljs-number">741</span>,<span class="hljs-number">852</span>]<br>nums_plus=nums*<span class="hljs-number">2</span><br><br><span class="hljs-comment"># 统计某一元素出现次数</span><br><span class="hljs-keyword">if</span> <span class="hljs-number">147</span> <span class="hljs-keyword">in</span> nums_plus :<br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">"147出现次数为\t:"</span>+ <span class="hljs-built_in">str</span>(nums_plus.count(<span class="hljs-number">147</span>)))<br><span class="hljs-keyword">else</span>:<br>    <span class="hljs-built_in">print</span>(<span class="hljs-built_in">str</span>(<span class="hljs-number">147</span>)+<span class="hljs-string">"不存在"</span>)<br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">"nums和:"</span>+<span class="hljs-built_in">str</span>(<span class="hljs-built_in">sum</span>(nums))+<span class="hljs-string">"\nnums_plus和为\t:"</span>+<span class="hljs-built_in">str</span>(<span class="hljs-built_in">sum</span>(nums_plus)))<br><br></code></pre></td></tr></tbody></table></figure></li>
</ul>
<blockquote>
<p>str ( value ) ：强行转换为字符串。print操作必须全部为字符串，如果不转换，则会提示数字无法与字符串相加。</p>
</blockquote>
<h4 id="4-1-6-列表的排序"><a href="#4-1-6-列表的排序" class="headerlink" title="4.1.6 列表的排序"></a>4.1.6 列表的排序</h4><ul>
<li><p>sort。在原列表上排序。<code>listname.sort()</code> 或 <code>listname.sort( key=None ,reserve=False)</code></p>
<blockquote>
<p>​        后者括号中的两项都可以省略。</p>
<p>​        第一项为指定排序时是否忽略大小写。<code>key=None</code> 或<code>key=str.functionName</code> 这项的意思是，指定排序时每个列表元素进行的转换。 </p>
<p>​        第二项为指定排序是否为逆序的。</p>
</blockquote>
</li>
<li><p>sorted。返回已排序的列表。<code>sort(listname)</code> 或 <code>sorted ( listname , key = None ,reserve = False )</code> </p>
<blockquote>
<p>规则同上。</p>
</blockquote>
  <figure class="highlight python"><table><tbody><tr><td class="code"><pre class=" language-hljs python"><span class="hljs-comment"># 定义一种排序 key</span><br><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">sortkey</span>(<span class="hljs-params">nu</span>):</span><br>    <span class="hljs-keyword">return</span> nu%<span class="hljs-number">10</span><br><br><span class="hljs-comment"># 定义俩序列</span><br>names=[<span class="hljs-string">"toms"</span>,<span class="hljs-string">"Jone"</span>,<span class="hljs-string">"Tony"</span>,<span class="hljs-string">"alice"</span>,<span class="hljs-string">"obma"</span>]<br>numbers=[<span class="hljs-number">123</span>,<span class="hljs-number">456</span>,<span class="hljs-number">852</span>,<span class="hljs-number">147</span>,<span class="hljs-number">369</span>,<span class="hljs-number">741</span>,<span class="hljs-number">963</span>]<br><br><span class="hljs-built_in">print</span>(<span class="hljs-string">"\n原序列names:"</span>)<br><span class="hljs-built_in">print</span>(names)<br><span class="hljs-built_in">print</span>(<span class="hljs-string">"\n原序列numbers:"</span>)<br><span class="hljs-built_in">print</span>(numbers)<br><br><span class="hljs-comment">#排序</span><br><span class="hljs-comment">#临时列表，保留原列表</span><br>term1=names<br>term2=numbers<br><br>term1.sort()<br>term2.sort()<br><span class="hljs-built_in">print</span>(<span class="hljs-string">"\n升序排列names(区分大小写)："</span>)<br><span class="hljs-built_in">print</span>(term1)<br><br><span class="hljs-comment">#添加key</span><br>term1=names<br>term1.sort(key=<span class="hljs-built_in">str</span>.lower) <span class="hljs-comment"># str.lower 字符串全部转换为小写的方法。</span><br><span class="hljs-built_in">print</span>(<span class="hljs-string">"\n升序排列names(不区分大小写)："</span>)<br><span class="hljs-built_in">print</span>(term1)<br><br><span class="hljs-built_in">print</span>(<span class="hljs-string">"\n升序排列numbers："</span>)<br>term2=numbers<br><span class="hljs-built_in">print</span>(term2)<span class="hljs-comment"># 原列表</span><br>term2.sort(key=sortKey)<span class="hljs-comment"># 按照开头定义的key排序</span><br><span class="hljs-built_in">print</span>(term2)<span class="hljs-comment"># 排序后</span><br><br><span class="hljs-built_in">print</span>(<span class="hljs-string">"\n降序排列numbers："</span>)<br>term1=numbers<br>term2= <span class="hljs-built_in">sorted</span>(term1,key=sortKey,reverse=<span class="hljs-literal">True</span>)<br><span class="hljs-built_in"><code class="language-hljs python"><span class="hljs-comment"># 定义一种排序 key</span><br><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">sortkey</span>(<span class="hljs-params">nu</span>):</span><br>    <span class="hljs-keyword">return</span> nu%<span class="hljs-number">10</span><br><br><span class="hljs-comment"># 定义俩序列</span><br>names=[<span class="hljs-string">"toms"</span>,<span class="hljs-string">"Jone"</span>,<span class="hljs-string">"Tony"</span>,<span class="hljs-string">"alice"</span>,<span class="hljs-string">"obma"</span>]<br>numbers=[<span class="hljs-number">123</span>,<span class="hljs-number">456</span>,<span class="hljs-number">852</span>,<span class="hljs-number">147</span>,<span class="hljs-number">369</span>,<span class="hljs-number">741</span>,<span class="hljs-number">963</span>]<br><br><span class="hljs-built_in">print</span>(<span class="hljs-string">"\n原序列names:"</span>)<br><span class="hljs-built_in">print</span>(names)<br><span class="hljs-built_in">print</span>(<span class="hljs-string">"\n原序列numbers:"</span>)<br><span class="hljs-built_in">print</span>(numbers)<br><br><span class="hljs-comment">#排序</span><br><span class="hljs-comment">#临时列表，保留原列表</span><br>term1=names<br>term2=numbers<br><br>term1.sort()<br>term2.sort()<br><span class="hljs-built_in">print</span>(<span class="hljs-string">"\n升序排列names(区分大小写)："</span>)<br><span class="hljs-built_in">print</span>(term1)<br><br><span class="hljs-comment">#添加key</span><br>term1=names<br>term1.sort(key=<span class="hljs-built_in">str</span>.lower) <span class="hljs-comment"># str.lower 字符串全部转换为小写的方法。</span><br><span class="hljs-built_in">print</span>(<span class="hljs-string">"\n升序排列names(不区分大小写)："</span>)<br><span class="hljs-built_in">print</span>(term1)<br><br><span class="hljs-built_in">print</span>(<span class="hljs-string">"\n升序排列numbers："</span>)<br>term2=numbers<br><span class="hljs-built_in">print</span>(term2)<span class="hljs-comment"># 原列表</span><br>term2.sort(key=sortKey)<span class="hljs-comment"># 按照开头定义的key排序</span><br><span class="hljs-built_in">print</span>(term2)<span class="hljs-comment"># 排序后</span><br><br><span class="hljs-built_in">print</span>(<span class="hljs-string">"\n降序排列numbers："</span>)<br>term1=numbers<br>term2= <span class="hljs-built_in">sorted</span>(term1,key=sortKey,reverse=<span class="hljs-literal">True</span>)<br><span class="hljs-built_in">print</span>(term2)<br></code></pre></td></tr></tbody></table></figure></li>
</ul>
<h3 id="4-2-元组"><a href="#4-2-元组" class="headerlink" title="4.2 元组"></a>4.2 元组</h3><ul>
<li>元组不能对元素赋值，即修改，不能删除一个或多个元素，只能整个删除。若要修改，可以整个元组重新赋值。</li>
<li>元组可进行组合，直接进行 + ，*。</li>
<li>列表的基本操作与常用方法元组也可使用。</li>
</ul>
<p>序列为’[]’,元组为’()’,字典为’{}’。</p>
<figure class="highlight python"><table><tbody><tr><td class="code"><pre class=" language-hljs python"><span class="hljs-comment"># encoding:utf-8</span><br>empty=()<br>num = <span class="hljs-number">156</span><br>st = <span class="hljs-string">"string_a"</span><br>one_index = [<span class="hljs-number">12</span>, <span class="hljs-number">45</span>, <span class="hljs-number">65</span>, <span class="hljs-number">78</span>]<br><br>tup1 = (<span class="hljs-string">"123456321"</span>,)<br><br><span class="hljs-comment">##? 声明一个很复杂的元组</span><br>tup2 = ( num, st, one_index)<br><br><span class="hljs-built_in">print</span>(<span class="hljs-string">"有一个元组为:"</span>,tup2)<br><br>tup3 = (<span class="hljs-string">"ab"</span>, <span class="hljs-string">"cd"</span>, <span class="hljs-string">"ef"</span>, <span class="hljs-number">98765132</span>, <span class="hljs-string">"#$%$&amp;"</span>)<br><br>alltuple = tup1 + tup2 + tup3<br><span class="hljs-built_in">print</span>(<span class="hljs-string">"组合后的元组："</span>,alltuple )<br><br><span class="hljs-comment">##? 输出指定序号元素</span><br>t = <span class="hljs-built_in">input</span>(<span class="hljs-string">"请输入元组序数"</span> + <span class="hljs-string">"1~"</span> + <span class="hljs-built_in">str</span>(<span class="hljs-built_in">len</span>(alltuple)))<br><span class="hljs-built_in">print</span>(alltuple[<span class="hljs-built_in">int</span>(t) - <span class="hljs-number">1</span>]) <span class="hljs-comment"><code class="language-hljs python"><span class="hljs-comment"># encoding:utf-8</span><br>empty=()<br>num = <span class="hljs-number">156</span><br>st = <span class="hljs-string">"string_a"</span><br>one_index = [<span class="hljs-number">12</span>, <span class="hljs-number">45</span>, <span class="hljs-number">65</span>, <span class="hljs-number">78</span>]<br><br>tup1 = (<span class="hljs-string">"123456321"</span>,)<br><br><span class="hljs-comment">##? 声明一个很复杂的元组</span><br>tup2 = ( num, st, one_index)<br><br><span class="hljs-built_in">print</span>(<span class="hljs-string">"有一个元组为:"</span>,tup2)<br><br>tup3 = (<span class="hljs-string">"ab"</span>, <span class="hljs-string">"cd"</span>, <span class="hljs-string">"ef"</span>, <span class="hljs-number">98765132</span>, <span class="hljs-string">"#$%$&amp;"</span>)<br><br>alltuple = tup1 + tup2 + tup3<br><span class="hljs-built_in">print</span>(<span class="hljs-string">"组合后的元组："</span>,alltuple )<br><br><span class="hljs-comment">##? 输出指定序号元素</span><br>t = <span class="hljs-built_in">input</span>(<span class="hljs-string">"请输入元组序数"</span> + <span class="hljs-string">"1~"</span> + <span class="hljs-built_in">str</span>(<span class="hljs-built_in">len</span>(alltuple)))<br><span class="hljs-built_in">print</span>(alltuple[<span class="hljs-built_in">int</span>(t) - <span class="hljs-number">1</span>]) <span class="hljs-comment"># 序号从 0 开始</span><br></code></pre></td></tr></tbody></table></figure>



<h3 id="4-3-字典"><a href="#4-3-字典" class="headerlink" title="4.3 字典"></a>4.3 字典</h3><p>类似于我们使用的字典，一个关键字，然后对应一些内容。查找时根据关键字查找。</p>
<h4 id="4-3-1-字典的生成"><a href="#4-3-1-字典的生成" class="headerlink" title="4.3.1 字典的生成"></a>4.3.1 字典的生成</h4><p>序列为’[]’,元组为’()’,字典为’{}’。</p>
<ul>
<li><p>直接赋值。 <code>dicti_b = {"拉丁语": "Latin", "鸟语": "!&amp;*/"}</code> </p>
</li>
<li><p>dict 生成。</p>
<blockquote>
<p>​        这里有个坑。如果组合的两部分不是元组或者列表，则合成的字典回事乱序的，且是随机组合的。即，用圆括号，或者方括号，别用花括号。</p>
</blockquote>
<figure class="highlight python"><table><tbody><tr><td class="code"><pre class=" language-hljs python">English = [<span class="hljs-string">"Chinese"</span>, <span class="hljs-string">"English"</span>, <span class="hljs-string">"Japanese"</span>, <span class="hljs-string">"Russian"</span>, <span class="hljs-string">"French"</span>, <span class="hljs-string">"German"</span>, <span class="hljs-string">"Korean"</span>]<br>Chinese = [<span class="hljs-string">"中文"</span>, <span class="hljs-string">"英语"</span>, <span class="hljs-string">"日语"</span>, <span class="hljs-string">"俄语"</span>, <span class="hljs-string">"法语"</span>, <span class="hljs-string">"德语"</span>, <span class="hljs-string">"韩语"</span>]<br><br>didi = <span class="hljs-built_in">zip</span>(Chinese, English)<br>dicti= <span class="hljs-built_in"><code class="language-hljs python">English = [<span class="hljs-string">"Chinese"</span>, <span class="hljs-string">"English"</span>, <span class="hljs-string">"Japanese"</span>, <span class="hljs-string">"Russian"</span>, <span class="hljs-string">"French"</span>, <span class="hljs-string">"German"</span>, <span class="hljs-string">"Korean"</span>]<br>Chinese = [<span class="hljs-string">"中文"</span>, <span class="hljs-string">"英语"</span>, <span class="hljs-string">"日语"</span>, <span class="hljs-string">"俄语"</span>, <span class="hljs-string">"法语"</span>, <span class="hljs-string">"德语"</span>, <span class="hljs-string">"韩语"</span>]<br><br>didi = <span class="hljs-built_in">zip</span>(Chinese, English)<br>dicti= <span class="hljs-built_in">dict</span>(didi)<br></code></pre></td></tr></tbody></table></figure></li>
</ul>
<figure class="highlight python"><table><tbody><tr><td class="code"><pre class=" language-hljs python"><span class="hljs-comment"># 输出 clear 后的字典 d 中的元素及个数</span><br><span class="hljs-built_in">print</span>(<span class="hljs-string">"dicti_c clear()后"</span> + <span class="hljs-string">"dicti_c还有"</span> + <span class="hljs-built_in">str</span>(<span class="hljs-built_in">len</span>(dicti_c)) + <span class="hljs-string">"个元素"</span>)<br><span class="hljs-built_in">print</span>(dicti_c)<br><br><span class="hljs-comment"># del用于删除对象</span><br><span class="hljs-keyword">del</span> dicti_d<br><span class="hljs-built_in">print</span>(<span class="hljs-string"><code class="language-hljs python"><span class="hljs-comment"># 输出 clear 后的字典 d 中的元素及个数</span><br><span class="hljs-built_in">print</span>(<span class="hljs-string">"dicti_c clear()后"</span> + <span class="hljs-string">"dicti_c还有"</span> + <span class="hljs-built_in">str</span>(<span class="hljs-built_in">len</span>(dicti_c)) + <span class="hljs-string">"个元素"</span>)<br><span class="hljs-built_in">print</span>(dicti_c)<br><br><span class="hljs-comment"># del用于删除对象</span><br><span class="hljs-keyword">del</span> dicti_d<br><span class="hljs-built_in">print</span>(<span class="hljs-string">"delete后的 e"</span>)<br></code></pre></td></tr></tbody></table></figure>





<h4 id="4-3-2-字典基本操作"><a href="#4-3-2-字典基本操作" class="headerlink" title="4.3.2 字典基本操作"></a>4.3.2 字典基本操作</h4><p>先 生成一个字典。</p>
<figure class="highlight python"><table><tbody><tr><td class="code"><pre class=" language-hljs python">name = (<span class="hljs-string">"吴晓咖"</span>,<span class="hljs-string">"刘佳怡"</span>,<span class="hljs-string">"徐之才"</span>,<span class="hljs-string">"单久思"</span>,<span class="hljs-string">"曹侃儿"</span>,<span class="hljs-string">"开俊峰"</span>,<span class="hljs-string">"倪吉本"</span>,<span class="hljs-string">"苗人凤"</span>,<span class="hljs-string">"荣家达"</span>,<span class="hljs-string">"狄俊娥"</span>,<span class="hljs-string">"牛春波"</span>,<span class="hljs-string">"莫桑石"</span>,)<br>sign = (<span class="hljs-string">"子鼠"</span>, <span class="hljs-string">"丑牛"</span>, <span class="hljs-string">"寅虎"</span>, <span class="hljs-string">"卯兔"</span>, <span class="hljs-string">"辰龙"</span>, <span class="hljs-string">"巳蛇"</span>, <span class="hljs-string">"午马"</span>, <span class="hljs-string">"未羊"</span>, <span class="hljs-string">"申猴"</span>, <span class="hljs-string">"酉鸡"</span>, <span class="hljs-string">"戌狗"</span>, <span class="hljs-string">"亥猪"</span>)<br><span class="hljs-comment"># 生成。</span><br>roster = <span class="hljs-built_in">dict</span>( <span class="hljs-built_in">zip</span>(name, sign))<br><span class="hljs-built_in"><code class="language-hljs python">name = (<span class="hljs-string">"吴晓咖"</span>,<span class="hljs-string">"刘佳怡"</span>,<span class="hljs-string">"徐之才"</span>,<span class="hljs-string">"单久思"</span>,<span class="hljs-string">"曹侃儿"</span>,<span class="hljs-string">"开俊峰"</span>,<span class="hljs-string">"倪吉本"</span>,<span class="hljs-string">"苗人凤"</span>,<span class="hljs-string">"荣家达"</span>,<span class="hljs-string">"狄俊娥"</span>,<span class="hljs-string">"牛春波"</span>,<span class="hljs-string">"莫桑石"</span>,)<br>sign = (<span class="hljs-string">"子鼠"</span>, <span class="hljs-string">"丑牛"</span>, <span class="hljs-string">"寅虎"</span>, <span class="hljs-string">"卯兔"</span>, <span class="hljs-string">"辰龙"</span>, <span class="hljs-string">"巳蛇"</span>, <span class="hljs-string">"午马"</span>, <span class="hljs-string">"未羊"</span>, <span class="hljs-string">"申猴"</span>, <span class="hljs-string">"酉鸡"</span>, <span class="hljs-string">"戌狗"</span>, <span class="hljs-string">"亥猪"</span>)<br><span class="hljs-comment"># 生成。</span><br>roster = <span class="hljs-built_in">dict</span>( <span class="hljs-built_in">zip</span>(name, sign))<br><span class="hljs-built_in">print</span>(roster)<br></code></pre></td></tr></tbody></table></figure>

<ul>
<li><p>取值。直接用 key 获取。或者使用 get() 方法。</p>
<blockquote>
<p>​        如果key不存在，则会报错。所以可结合 in 操作。或者get()方法。</p>
<p>get()方法获取的key不存在时会返回none。</p>
</blockquote>
<figure class="highlight python"><table><tbody><tr><td class="code"><pre class=" language-hljs python"><span class="hljs-built_in">print</span>(roster[<span class="hljs-string">"徐之才"</span>])<br><span class="hljs-built_in">print</span>(roster.get(<span class="hljs-string"><code class="language-hljs python"><span class="hljs-built_in">print</span>(roster[<span class="hljs-string">"徐之才"</span>])<br><span class="hljs-built_in">print</span>(roster.get(<span class="hljs-string">"徐才"</span>))<br></code></pre></td></tr></tbody></table></figure></li>
<li><p>添加。通过赋值的形式。<code>roster[key_name] = key_value</code></p>
</li>
<li><p>删除。使用 del 操作。<code>del roster[ “徐之才” ]</code></p>
</li>
<li><p>清除。 clear() 。清除字典里的所有项。<code>dictionaryName.clear()</code>。</p>
</li>
<li><p>遍历。</p>
<figure class="highlight python"><table><tbody><tr><td class="code"><pre class=" language-hljs python"><span class="hljs-comment"># 遍历输出值</span><br><span class="hljs-keyword">for</span> xxoo <span class="hljs-keyword">in</span> roster.items():<br>    <span class="hljs-built_in">print</span>(xxoo)<br><span class="hljs-comment"># 只输出值，不输出标签的遍历。</span><br><span class="hljs-keyword">for</span> ooxx <span class="hljs-keyword">in</span> roster.keys():<br>    <span class="hljs-built_in">print</span>(ooxx)<br><span class="hljs-comment"># 值与标签双遍历。</span><br><span class="hljs-keyword">for</span> key, value <span class="hljs-keyword">in</span> roster.items():<br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">"键是："</span> + key + <span class="hljs-string"><code class="language-hljs python"><span class="hljs-comment"># 遍历输出值</span><br><span class="hljs-keyword">for</span> xxoo <span class="hljs-keyword">in</span> roster.items():<br>    <span class="hljs-built_in">print</span>(xxoo)<br><span class="hljs-comment"># 只输出值，不输出标签的遍历。</span><br><span class="hljs-keyword">for</span> ooxx <span class="hljs-keyword">in</span> roster.keys():<br>    <span class="hljs-built_in">print</span>(ooxx)<br><span class="hljs-comment"># 值与标签双遍历。</span><br><span class="hljs-keyword">for</span> key, value <span class="hljs-keyword">in</span> roster.items():<br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">"键是："</span> + key + <span class="hljs-string">"值为："</span> + value)<br></code></pre></td></tr></tbody></table></figure></li>
</ul>
<h3 id="4-4-字符串"><a href="#4-4-字符串" class="headerlink" title="4.4 字符串"></a>4.4 字符串</h3><p>定义两个字符串</p>
<figure class="highlight python"><table><tbody><tr><td class="code"><pre class=" language-hljs python">poem_first = <span class="hljs-string">"老夫聊发少年狂，左牵黄，右擎苍，锦帽貂裘，千骑卷平冈。为报倾城随太守，亲射虎，看孙郎。"</span><br>poem_second = <span class="hljs-string">"酒酣胸胆尚开张。鬓微霜，又何妨！持节云中，何日遣冯唐？会挽雕弓如满月，西北望，射天狼。"</span><br>letter = <span class="hljs-string"><code class="language-hljs python">poem_first = <span class="hljs-string">"老夫聊发少年狂，左牵黄，右擎苍，锦帽貂裘，千骑卷平冈。为报倾城随太守，亲射虎，看孙郎。"</span><br>poem_second = <span class="hljs-string">"酒酣胸胆尚开张。鬓微霜，又何妨！持节云中，何日遣冯唐？会挽雕弓如满月，西北望，射天狼。"</span><br>letter = <span class="hljs-string">"  \n  Transportation has been greatly changed in the past few years. In ancient days, people used to travel by horse or carriage. \n    \t"</span><br></code></pre></td></tr></tbody></table></figure>

<h4 id="4-4-0-字符串读取"><a href="#4-4-0-字符串读取" class="headerlink" title="4.4.0 字符串读取"></a>4.4.0 字符串读取</h4><ul>
<li>切片操作。</li>
<li>完全读取，当个变量。</li>
</ul>
<h4 id="4-4-1-字符串基本操作"><a href="#4-4-1-字符串基本操作" class="headerlink" title="4.4.1 字符串基本操作"></a>4.4.1 字符串基本操作</h4><ul>
<li><p>计算字符串长度。<code>len(str) </code></p>
</li>
<li><p>拼接。使用+操作。<code>str1+str2</code></p>
<figure class="highlight python"><table><tbody><tr><td class="code"><pre class=" language-hljs python"><code class="language-hljs python">str_s = poem_first + poem_second<br></code></pre></td></tr></tbody></table></figure></li>
<li><p>去除。</p>
<ul>
<li><p>截取。<code>string [start : end : step]</code> </p>
<figure class="highlight python"><table><tbody><tr><td class="code"><pre class=" language-hljs python"><span class="hljs-built_in">print</span>(<span class="hljs-string">"分片字符串为:"</span>, poem_first[<span class="hljs-number">0</span>:<span class="hljs-number">21</span>:<span class="hljs-number">4</span>]) <span class="hljs-comment"><code class="language-hljs python"><span class="hljs-built_in">print</span>(<span class="hljs-string">"分片字符串为:"</span>, poem_first[<span class="hljs-number">0</span>:<span class="hljs-number">21</span>:<span class="hljs-number">4</span>]) <span class="hljs-comment"># 0~20，每4个字符截断一次。</span><br></code></pre></td></tr></tbody></table></figure>

<blockquote>
<p>end 为最后一个字符的后一个索引。即表示到哪个字符之前。</p>
<p>step 为截断字符串的长度。</p>
</blockquote>
</li>
<li><p>替换。strip()、lstrip()、rstrip()、upper()、lower()、replace()</p>
<p><code>str.strip([chars])</code>—— 去除字符串左右侧的空格和特殊字符。</p>
<p><code>str.lstrip([chars])</code>—— 去掉左侧空格和特殊字符。</p>
<p><code>str.rstrip([chars])</code>—— 去掉右侧空格和特殊字符。</p>
<p><code>str.upper()</code> —— 全部变大写</p>
<p><code>str.lower()</code>—— 全部变小写</p>
<p><code>str.replace(oldchar,newchar)</code> —— 用 newchar 替换 oldchar，返回替换后的字符串。</p>
<figure class="highlight python"><table><tbody><tr><td class="code"><pre class=" language-hljs python"><span class="hljs-comment"># 去除两侧空格或特殊字符</span><br><span class="hljs-built_in">print</span>(<span class="hljs-string">"\n英语作文去空格:\t"</span>, letter.strip(<span class="hljs-string">" "</span>))<br><span class="hljs-comment"># 去除左侧空格或特殊字符</span><br><span class="hljs-built_in">print</span>(<span class="hljs-string">"\n英语作文去空格:\t"</span>, letter.lstrip(<span class="hljs-string">" "</span>))<br>letter.replace(<span class="hljs-string">"@"</span>,<span class="hljs-string"><code class="language-hljs python"><span class="hljs-comment"># 去除两侧空格或特殊字符</span><br><span class="hljs-built_in">print</span>(<span class="hljs-string">"\n英语作文去空格:\t"</span>, letter.strip(<span class="hljs-string">" "</span>))<br><span class="hljs-comment"># 去除左侧空格或特殊字符</span><br><span class="hljs-built_in">print</span>(<span class="hljs-string">"\n英语作文去空格:\t"</span>, letter.lstrip(<span class="hljs-string">" "</span>))<br>letter.replace(<span class="hljs-string">"@"</span>,<span class="hljs-string">"t"</span>)<br></code></pre></td></tr></tbody></table></figure>

<blockquote>
<p>​        str：要操作的字符串，chars可选：要去掉的字符或者字符串，默认去掉换行、空格、回车、制表符。</p>
<p>​        后两个方法，一个去除左侧的，一个去除右侧的。</p>
</blockquote>
</li>
</ul>
</li>
<li><p>转换。</p>
<ul>
<li><p>分割。<code>split(sep, maxsplit)</code></p>
<figure class="highlight python"><table><tbody><tr><td class="code"><pre class=" language-hljs python">strs = poem_first.split(<span class="hljs-string">"。"</span>, -<span class="hljs-number">1</span>)<br><span class="hljs-built_in">print</span>(<span class="hljs-string">"整首诗按句号分割为："</span>)<br><span class="hljs-keyword">for</span> linshi <span class="hljs-keyword">in</span> strs:<br>    <span class="hljs-built_in">print</span>(<span class="hljs-string"><code class="language-hljs python">strs = poem_first.split(<span class="hljs-string">"。"</span>, -<span class="hljs-number">1</span>)<br><span class="hljs-built_in">print</span>(<span class="hljs-string">"整首诗按句号分割为："</span>)<br><span class="hljs-keyword">for</span> linshi <span class="hljs-keyword">in</span> strs:<br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">"@"</span> + linshi)<br></code></pre></td></tr></tbody></table></figure>

<blockquote>
<p>​        sep : 分割的字符或字符串，默认为空格换行符之类的。</p>
<p>需要注意，sep在分割后狙消失了。</p>
<p>​        maxsplit：分割的次数。默认为能割几次割几次。<code>-1</code> 效果一样。</p>
<p>需要注意，<code>maxsplit</code>为分割次数，产生<code>maxsplit +1</code>项</p>
</blockquote>
</li>
</ul>
</li>
</ul>
<figure class="highlight python"><table><tbody><tr><td class="code"><pre class=" language-hljs python"><span class="hljs-comment">#  以 GBK 编码格式输出字符串长度</span><br><span class="hljs-built_in">print</span>(<span class="hljs-string">"\nGBK计数长度为："</span> + <span class="hljs-built_in">str</span>(<span class="hljs-built_in">len</span>(poem_first.encode(<span class="hljs-string">"gbk"</span>))))<br><br><span class="hljs-comment">#  以 UTF-8 编码格式输出字符串长度</span><br><span class="hljs-built_in">print</span>(<span class="hljs-string">"\nUTF-8计数长度为："</span> + <span class="hljs-built_in">str</span>(<span class="hljs-built_in"><code class="language-hljs python"><span class="hljs-comment">#  以 GBK 编码格式输出字符串长度</span><br><span class="hljs-built_in">print</span>(<span class="hljs-string">"\nGBK计数长度为："</span> + <span class="hljs-built_in">str</span>(<span class="hljs-built_in">len</span>(poem_first.encode(<span class="hljs-string">"gbk"</span>))))<br><br><span class="hljs-comment">#  以 UTF-8 编码格式输出字符串长度</span><br><span class="hljs-built_in">print</span>(<span class="hljs-string">"\nUTF-8计数长度为："</span> + <span class="hljs-built_in">str</span>(<span class="hljs-built_in">len</span>(poem_first.encode())))<br></code></pre></td></tr></tbody></table></figure>



<h4 id="4-4-2-字符串检索-amp-索引"><a href="#4-4-2-字符串检索-amp-索引" class="headerlink" title="4.4.2 字符串检索&amp;索引"></a>4.4.2 字符串检索&amp;索引</h4><ul>
<li><p>定义字符串</p>
<figure class="highlight python"><table><tbody><tr><td class="code"><pre class=" language-hljs python">mulanshi = <span class="hljs-string">"唧唧复唧唧，木兰当户织。不闻机杼声，唯闻女叹息。问女何所思，问女何所忆。女亦无所思，女亦无所忆。昨夜见军帖，可汗大点兵，军书十二卷，卷卷有爷名。阿爷无大儿，木兰无长兄，愿为市鞍马，从此替爷征。东市买骏马，西市买鞍鞯，南市买辔头，北市买长鞭。旦辞爷娘去，暮宿黄河边，不闻爷娘唤女声，但闻黄河流水鸣溅溅。旦辞黄河去，暮至黑山头，不闻爷娘唤女声，但闻燕山胡骑鸣啾啾。万里赴戎机，关山度若飞。朔气传金柝，寒光照铁衣。将军百战死，壮士十年归。归来见天子，天子坐明堂。策勋十二转，赏赐百千强。可汗问所欲，木兰不用尚书郎，愿驰千里足，送儿还故乡。爷娘闻女来，出郭相扶将；阿姊闻妹来，当户理红妆；小弟闻姊来，磨刀霍霍向猪羊。开我东阁门，坐我西阁床，脱我战时袍，著我旧时裳。当窗理云鬓，对镜帖花黄。出门看火伴，火伴皆惊忙：同行十二年，不知木兰是女郎。雄兔脚扑朔，雌兔眼迷离；双兔傍地走，安能辨我是雄雌？"</span><br><span class="hljs-comment"># 目标字符串</span><br>mulan = <span class="hljs-string">"木兰"</span><br><span class="hljs-comment"><code class="language-hljs python">mulanshi = <span class="hljs-string">"唧唧复唧唧，木兰当户织。不闻机杼声，唯闻女叹息。问女何所思，问女何所忆。女亦无所思，女亦无所忆。昨夜见军帖，可汗大点兵，军书十二卷，卷卷有爷名。阿爷无大儿，木兰无长兄，愿为市鞍马，从此替爷征。东市买骏马，西市买鞍鞯，南市买辔头，北市买长鞭。旦辞爷娘去，暮宿黄河边，不闻爷娘唤女声，但闻黄河流水鸣溅溅。旦辞黄河去，暮至黑山头，不闻爷娘唤女声，但闻燕山胡骑鸣啾啾。万里赴戎机，关山度若飞。朔气传金柝，寒光照铁衣。将军百战死，壮士十年归。归来见天子，天子坐明堂。策勋十二转，赏赐百千强。可汗问所欲，木兰不用尚书郎，愿驰千里足，送儿还故乡。爷娘闻女来，出郭相扶将；阿姊闻妹来，当户理红妆；小弟闻姊来，磨刀霍霍向猪羊。开我东阁门，坐我西阁床，脱我战时袍，著我旧时裳。当窗理云鬓，对镜帖花黄。出门看火伴，火伴皆惊忙：同行十二年，不知木兰是女郎。雄兔脚扑朔，雌兔眼迷离；双兔傍地走，安能辨我是雄雌？"</span><br><span class="hljs-comment"># 目标字符串</span><br>mulan = <span class="hljs-string">"木兰"</span><br><span class="hljs-comment"># 操作字符串</span><br></code></pre></td></tr></tbody></table></figure></li>
<li><p>存在？</p>
<p>in 或 not in 可结合切片操作。</p>
<figure class="highlight python"><table><tbody><tr><td class="code"><pre class=" language-hljs python"><span class="hljs-comment">#  检测某一字符创是否存在于目标字符串（可以加入切片操作）</span><br><span class="hljs-built_in">print</span>(mulan <span class="hljs-keyword">in</span> mulanshi[<span class="hljs-number">0</span>:<span class="hljs-number">5</span>:])<br><span class="hljs-built_in">print</span>(mulan <span class="hljs-keyword">in</span> mulanshi[<span class="hljs-number">0</span>:<span class="hljs-number">10</span>:])<br><span class="hljs-built_in">print</span>(mulan <span class="hljs-keyword">not</span> <span class="hljs-keyword"><code class="language-hljs python"><span class="hljs-comment">#  检测某一字符创是否存在于目标字符串（可以加入切片操作）</span><br><span class="hljs-built_in">print</span>(mulan <span class="hljs-keyword">in</span> mulanshi[<span class="hljs-number">0</span>:<span class="hljs-number">5</span>:])<br><span class="hljs-built_in">print</span>(mulan <span class="hljs-keyword">in</span> mulanshi[<span class="hljs-number">0</span>:<span class="hljs-number">10</span>:])<br><span class="hljs-built_in">print</span>(mulan <span class="hljs-keyword">not</span> <span class="hljs-keyword">in</span> mulanshi)<br></code></pre></td></tr></tbody></table></figure></li>
<li><p>查找</p>
<p>find、rfind、index、count、startswith、endswith</p>
<figure class="highlight python"><table><tbody><tr><td class="code"><pre class=" language-hljs python"><span class="hljs-comment">#  find()   输出指定 “木兰” 在 “木兰诗” 中第一次出现的索引。</span><br><span class="hljs-built_in">print</span>(mulanshi.find(mulan, <span class="hljs-number">7</span>, <span class="hljs-number">390</span>))<br><span class="hljs-comment">#  rfind()  输出指定 “木兰” 在 “木兰诗” 中最后一次出现的索引。</span><br><span class="hljs-built_in">print</span>(mulanshi.rfind(mulan))<br><span class="hljs-comment">#  index()  输出“女”第一次出现的位置。</span><br><span class="hljs-built_in">print</span>(mulanshi.index(<span class="hljs-string">"女"</span>))<br><span class="hljs-comment">#  count()  输出“木兰”出现次数。</span><br><span class="hljs-built_in">print</span>(mulanshi.count(<span class="hljs-string">"木兰"</span>)<br><span class="hljs-comment">#  判断是否以指定字符串结尾或者开始。同样可加入切片。</span><br><span class="hljs-built_in">print</span>(<span class="hljs-string">"startswith:唧唧复唧唧"</span>,mulanshi.startswith(<span class="hljs-string">"唧唧复唧唧"</span>, <span class="hljs-number">0</span>, <span class="hljs-number">20</span>))<br><span class="hljs-built_in">print</span>(<span class="hljs-string">"startswith:雄雌？"</span>,mulanshi.endswith(<span class="hljs-string"><code class="language-hljs python"><span class="hljs-comment">#  find()   输出指定 “木兰” 在 “木兰诗” 中第一次出现的索引。</span><br><span class="hljs-built_in">print</span>(mulanshi.find(mulan, <span class="hljs-number">7</span>, <span class="hljs-number">390</span>))<br><span class="hljs-comment">#  rfind()  输出指定 “木兰” 在 “木兰诗” 中最后一次出现的索引。</span><br><span class="hljs-built_in">print</span>(mulanshi.rfind(mulan))<br><span class="hljs-comment">#  index()  输出“女”第一次出现的位置。</span><br><span class="hljs-built_in">print</span>(mulanshi.index(<span class="hljs-string">"女"</span>))<br><span class="hljs-comment">#  count()  输出“木兰”出现次数。</span><br><span class="hljs-built_in">print</span>(mulanshi.count(<span class="hljs-string">"木兰"</span>)<br><span class="hljs-comment">#  判断是否以指定字符串结尾或者开始。同样可加入切片。</span><br><span class="hljs-built_in">print</span>(<span class="hljs-string">"startswith:唧唧复唧唧"</span>,mulanshi.startswith(<span class="hljs-string">"唧唧复唧唧"</span>, <span class="hljs-number">0</span>, <span class="hljs-number">20</span>))<br><span class="hljs-built_in">print</span>(<span class="hljs-string">"startswith:雄雌？"</span>,mulanshi.endswith(<span class="hljs-string">"雄雌？"</span>))<br></code></pre></td></tr></tbody></table></figure>

<blockquote>
<p>​        rfind () 为从右开始查找。即返回最后一次出现的索引值。</p>
<p>所有的索引都是从 0 开 始。</p>
</blockquote>
</li>
</ul>
<h4 id="4-4-3-格式化字符串"><a href="#4-4-3-格式化字符串" class="headerlink" title="4.4.3 格式化字符串"></a>4.4.3 格式化字符串</h4><h5 id="4-4-3-1-格式"><a href="#4-4-3-1-格式" class="headerlink" title="4.4.3.1 % 格式"></a>4.4.3.1 % 格式</h5><p>% [ - ] [ + ] [ 0 ] [ m ] [ .n ] typecode</p>
<table>
<thead>
<tr>
<th align="center">符号</th>
<th align="left">作用</th>
</tr>
</thead>
<tbody><tr>
<td align="center">-</td>
<td align="left">左对齐，负数加符号，正数不变</td>
</tr>
<tr>
<td align="center">+</td>
<td align="left">右对齐，与上一个比，正数加正号。</td>
</tr>
<tr>
<td align="center">0</td>
<td align="left">右对齐，正不加。负加负号，0填充空白，一般与m同用</td>
</tr>
<tr>
<td align="center">m</td>
<td align="left">填充后的宽度。</td>
</tr>
<tr>
<td align="center">.n</td>
<td align="left">小数点后精度</td>
</tr>
</tbody></table>
<table>
<thead>
<tr>
<th align="left">typecode</th>
<th align="left">含义</th>
</tr>
</thead>
<tbody><tr>
<td align="left">%r</td>
<td align="left">字符串 (repr()显示)</td>
</tr>
<tr>
<td align="left">%g</td>
<td align="left">指数(e)或浮点数 (根据显示长度)</td>
</tr>
<tr>
<td align="left">%s</td>
<td align="left">字符串(str()显示)</td>
</tr>
<tr>
<td align="left">%G</td>
<td align="left">指数(E)或浮点数 (根据显示长度)</td>
</tr>
<tr>
<td align="left">%c</td>
<td align="left">单个字符输出</td>
</tr>
<tr>
<td align="left">% b 、o、d（i）、x</td>
<td align="left">二、八、十、十六进制整数</td>
</tr>
<tr>
<td align="left">% e（E）</td>
<td align="left">指数(基底写为e(E))</td>
</tr>
<tr>
<td align="left">% f (F)</td>
<td align="left">浮点数,与上相同</td>
</tr>
<tr>
<td align="left">%%</td>
<td align="left">字符”%”</td>
</tr>
</tbody></table>
<h5 id="4-4-3-2-代码"><a href="#4-4-3-2-代码" class="headerlink" title="4.4.3.2 %代码"></a>4.4.3.2 %代码</h5><figure class="highlight python"><table><tbody><tr><td class="code"><pre class=" language-hljs python">template_a = <span class="hljs-string">"%s \n市值:%07d 亿元\n网站：https://www.%s.com\n老总:%s\n"</span><br>temps = [<br>    ( <span class="hljs-string">"百度"</span>,<span class="hljs-number">3873</span>, <span class="hljs-string">"baidu"</span>, <span class="hljs-string">"李彦宏"</span>),<br>    (<span class="hljs-string">"阿里巴巴"</span>,<span class="hljs-number">24500</span>,  <span class="hljs-string">"alibaba"</span>, <span class="hljs-string">"马云"</span>),<br>    (<span class="hljs-string">"腾讯"</span>,<span class="hljs-number">44200</span>,  <span class="hljs-string">"tencent"</span>, <span class="hljs-string">"马化腾"</span>),<br>]<br><span class="hljs-keyword">for</span> ls <span class="hljs-keyword">in</span> temps:<br>    <span class="hljs-built_in"><code class="language-hljs python">template_a = <span class="hljs-string">"%s \n市值:%07d 亿元\n网站：https://www.%s.com\n老总:%s\n"</span><br>temps = [<br>    ( <span class="hljs-string">"百度"</span>,<span class="hljs-number">3873</span>, <span class="hljs-string">"baidu"</span>, <span class="hljs-string">"李彦宏"</span>),<br>    (<span class="hljs-string">"阿里巴巴"</span>,<span class="hljs-number">24500</span>,  <span class="hljs-string">"alibaba"</span>, <span class="hljs-string">"马云"</span>),<br>    (<span class="hljs-string">"腾讯"</span>,<span class="hljs-number">44200</span>,  <span class="hljs-string">"tencent"</span>, <span class="hljs-string">"马化腾"</span>),<br>]<br><span class="hljs-keyword">for</span> ls <span class="hljs-keyword">in</span> temps:<br>    <span class="hljs-built_in">print</span>(template_a % ls)<br></code></pre></td></tr></tbody></table></figure>

<blockquote>
<p>如代码所示，先声明一个模板，然后再套用。</p>
<ul>
<li>制作模板。用以上的符号加其他字符串组成。</li>
<li>套用。模板 % 目标字符串即可。</li>
</ul>
<p>提醒，这种方式为最早的方案，目前官方主推下边的format方式。</p>
</blockquote>
<h5 id="4-4-3-3-format-格式"><a href="#4-4-3-3-format-格式" class="headerlink" title="4.4.3.3 format 格式"></a>4.4.3.3 format 格式</h5><p>{  [ index ] <b style="color:#EF19E5"> [ <b style="color:#40D72F"> [ :&nbsp;<b style="color:#8417F7">[ fill ] align&nbsp;</b> ] [&nbsp;sign ]&nbsp; [ # ] [&nbsp;width ]&nbsp; [ .precision ] [&nbsp;type ] </b> ]</b>  }</p>
<table>
<thead>
<tr>
<th align="left">位置符号</th>
<th align="left">作用</th>
</tr>
</thead>
<tbody><tr>
<td align="left">index</td>
<td align="left">默认按顺序自动分配。可选参数，指定索引位置，从0开始。</td>
</tr>
<tr>
<td align="left">fill</td>
<td align="left">可选参数，空白处填充的字符。</td>
</tr>
<tr>
<td align="left">align</td>
<td align="left">可选参数， 用于指定对齐方式。</td>
</tr>
<tr>
<td align="left">&lt;</td>
<td align="left">左对齐。</td>
</tr>
<tr>
<td align="left">&gt;</td>
<td align="left">右对齐。</td>
</tr>
<tr>
<td align="left">^</td>
<td align="left">居中对齐。需指定宽度。</td>
</tr>
<tr>
<td align="left">=</td>
<td align="left">右对齐。只对数字类型有用，尤其用于输出负数。</td>
</tr>
<tr>
<td align="left"><br>sign</td>
<td align="left">可选参数，用于指定有无符号数<br>‘+’：正数添加‘+’号,负数添加‘-’号。<br>‘-‘：只有负号添加符号。<br>‘ ‘:正数加空格补齐，负数加负号</td>
</tr>
<tr>
<td align="left">#</td>
<td align="left">可选参数，加#时输出二、八、十六进制会添加  0b  0o  0x 前缀</td>
</tr>
</tbody></table>
<table>
<thead>
<tr>
<th align="left">type</th>
<th align="left">…….</th>
</tr>
</thead>
<tbody><tr>
<td align="left">type</td>
<td align="left">含义</td>
</tr>
<tr>
<td align="left">s</td>
<td align="left">对字符串格式格式化</td>
</tr>
<tr>
<td align="left">b</td>
<td align="left">十进制数转换为二进制再格式化；</td>
</tr>
<tr>
<td align="left">d</td>
<td align="left">十进制数</td>
</tr>
<tr>
<td align="left">o</td>
<td align="left">十进制数转换为八进制再格式化；</td>
</tr>
<tr>
<td align="left">c</td>
<td align="left">十进制数转换为对应Unicode字符</td>
</tr>
<tr>
<td align="left">%</td>
<td align="left">显示百分比(默认小数后六位)</td>
</tr>
<tr>
<td align="left">x,X</td>
<td align="left">十进制数转换为十六进制再格式化</td>
</tr>
<tr>
<td align="left">e,E</td>
<td align="left">转换为科学计数法再格式化</td>
</tr>
<tr>
<td align="left">f,F</td>
<td align="left">转换为浮点数再格式化(默认六位小数)</td>
</tr>
<tr>
<td align="left">g,G</td>
<td align="left">e与f或E与F之间互换</td>
</tr>
</tbody></table>
<h5 id="4-4-3-4-代码"><a href="#4-4-3-4-代码" class="headerlink" title="4.4.3.4 代码"></a>4.4.3.4 代码</h5><figure class="highlight python"><table><tbody><tr><td class="code"><pre class=" language-hljs python">strin1 = <span class="hljs-string">"\n马云,\t身价:\t{0:,.2f}"</span>.<span class="hljs-built_in">format</span>(<span class="hljs-number">13.4567</span>)<br>strin2 = <span class="hljs-string">"\n刘强东,\t身价:\t{0:.3f}\n"</span>.<span class="hljs-built_in">format</span>(<span class="hljs-number">21.5153</span>)<br>strin3 = <span class="hljs-string">"""\nπ为：{:.3f}\n'101'二进制：{:#b}\n'101'八进制：{:#o}\n'101'十六进制：{:#x}\n"""</span>.<span class="hljs-built_in">format</span>(<span class="hljs-number">3.14159</span>, <span class="hljs-number">101</span>,<span class="hljs-number">101</span>,<span class="hljs-number">101</span> )<br>strin4 = <span class="hljs-string">"""\nabc：{abc}\nbcd：{bcd:#x}\ncde：{cde:}\n"""</span>.<span class="hljs-built_in">format</span>(abc=<span class="hljs-string">"11211"</span>, bcd=<span class="hljs-number">121</span>, cde=[<span class="hljs-number">123</span>, <span class="hljs-number">456</span>, <span class="hljs-number">789</span>])<br><span class="hljs-built_in"><code class="language-hljs python">strin1 = <span class="hljs-string">"\n马云,\t身价:\t{0:,.2f}"</span>.<span class="hljs-built_in">format</span>(<span class="hljs-number">13.4567</span>)<br>strin2 = <span class="hljs-string">"\n刘强东,\t身价:\t{0:.3f}\n"</span>.<span class="hljs-built_in">format</span>(<span class="hljs-number">21.5153</span>)<br>strin3 = <span class="hljs-string">"""\nπ为：{:.3f}\n'101'二进制：{:#b}\n'101'八进制：{:#o}\n'101'十六进制：{:#x}\n"""</span>.<span class="hljs-built_in">format</span>(<span class="hljs-number">3.14159</span>, <span class="hljs-number">101</span>,<span class="hljs-number">101</span>,<span class="hljs-number">101</span> )<br>strin4 = <span class="hljs-string">"""\nabc：{abc}\nbcd：{bcd:#x}\ncde：{cde:}\n"""</span>.<span class="hljs-built_in">format</span>(abc=<span class="hljs-string">"11211"</span>, bcd=<span class="hljs-number">121</span>, cde=[<span class="hljs-number">123</span>, <span class="hljs-number">456</span>, <span class="hljs-number">789</span>])<br><span class="hljs-built_in">print</span>(strin1,strin2,strin3,strin4)<br></code></pre></td></tr></tbody></table></figure>

<blockquote>
<p>如上所示，使用方法为字符串后加 “.” 然后 format（）嵌入数值。有演示的两种方法：</p>
<ul>
<li>按照顺序，依次列出。</li>
<li>指定名称，然后根据名称依次赋值。</li>
</ul>
</blockquote>
<h2 id="5-正则表达式"><a href="#5-正则表达式" class="headerlink" title="5. 正则表达式"></a>5. 正则表达式</h2><p>基础正则了解：<a style="font-family:’kaiti’;">[点我]([正则语法整理 | X-Y-Z`s Blog (gitee.io)](https://blogofxyz.gitee.io/2021/08/14/正则语法整理/))</a></p>
<h3 id="5-1-匹配"><a href="#5-1-匹配" class="headerlink" title="5.1 匹配"></a>5.1 匹配</h3><ul>
<li><p>match</p>
<figure class="highlight python"><table><tbody><tr><td class="code"><pre class=" language-hljs python"><span class="hljs-keyword">import</span> re<br>elements = [<br>    <span class="hljs-string">"15946295618"</span>,<br>    <span class="hljs-string">"78945631245"</span>,<br>    <span class="hljs-string">"48651534582@qq.com"</span>,<br>    <span class="hljs-string">"12348621@163.com"</span> ,<br>    <span class="hljs-string">"15648934529@gmail.com"</span>,<br>    <span class="hljs-string">"萨博隔热垫石膏板"</span>,<br>    <span class="hljs-string">"调查表身高多少"</span>,<br>]<br>regular_express_a = [<br>    <span class="hljs-string">r"[0-9]{0,12}@(qq|gmail|163)\.com"</span>,<br>    <span class="hljs-string">r"1[0-9]{10}"</span>,<br>    <span class="hljs-string">r"[^0-9a-zA-Z]"</span>,<br>]<br><span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> elements:<br>    <span class="hljs-keyword">for</span> index, j <span class="hljs-keyword">in</span> <span class="hljs-built_in">enumerate</span>(regular_express_a):<br>        ret_a = re.match(j, i)<br>        <span class="hljs-keyword">if</span> ret_a != <span class="hljs-literal">None</span>:<br>            <span class="hljs-keyword">if</span> index == <span class="hljs-number">0</span>:<br>                <span class="hljs-built_in">print</span>(<span class="hljs-string">"邮箱:"</span>, i)<br>                <span class="hljs-keyword">break</span><br>            <span class="hljs-keyword">elif</span> index == <span class="hljs-number">1</span>:<br>                <span class="hljs-built_in">print</span>(<span class="hljs-string">"手机号:"</span>, i)<br>                <span class="hljs-keyword">break</span><br>            <span class="hljs-keyword">elif</span> index == <span class="hljs-number">2</span>:<br>                <span class="hljs-built_in">print</span>(<span class="hljs-string">"其他的合规字符串:"</span>, i)<br>                <span class="hljs-keyword">break</span><br>        <span class="hljs-keyword">else</span>:<br>            <span class="hljs-keyword"><code class="language-hljs python"><span class="hljs-keyword">import</span> re<br>elements = [<br>    <span class="hljs-string">"15946295618"</span>,<br>    <span class="hljs-string">"78945631245"</span>,<br>    <span class="hljs-string">"48651534582@qq.com"</span>,<br>    <span class="hljs-string">"12348621@163.com"</span> ,<br>    <span class="hljs-string">"15648934529@gmail.com"</span>,<br>    <span class="hljs-string">"萨博隔热垫石膏板"</span>,<br>    <span class="hljs-string">"调查表身高多少"</span>,<br>]<br>regular_express_a = [<br>    <span class="hljs-string">r"[0-9]{0,12}@(qq|gmail|163)\.com"</span>,<br>    <span class="hljs-string">r"1[0-9]{10}"</span>,<br>    <span class="hljs-string">r"[^0-9a-zA-Z]"</span>,<br>]<br><span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> elements:<br>    <span class="hljs-keyword">for</span> index, j <span class="hljs-keyword">in</span> <span class="hljs-built_in">enumerate</span>(regular_express_a):<br>        ret_a = re.match(j, i)<br>        <span class="hljs-keyword">if</span> ret_a != <span class="hljs-literal">None</span>:<br>            <span class="hljs-keyword">if</span> index == <span class="hljs-number">0</span>:<br>                <span class="hljs-built_in">print</span>(<span class="hljs-string">"邮箱:"</span>, i)<br>                <span class="hljs-keyword">break</span><br>            <span class="hljs-keyword">elif</span> index == <span class="hljs-number">1</span>:<br>                <span class="hljs-built_in">print</span>(<span class="hljs-string">"手机号:"</span>, i)<br>                <span class="hljs-keyword">break</span><br>            <span class="hljs-keyword">elif</span> index == <span class="hljs-number">2</span>:<br>                <span class="hljs-built_in">print</span>(<span class="hljs-string">"其他的合规字符串:"</span>, i)<br>                <span class="hljs-keyword">break</span><br>        <span class="hljs-keyword">else</span>:<br>            <span class="hljs-keyword">pass</span><br></code></pre></td></tr></tbody></table></figure>

<p>完全匹配字符串。不考虑换行，即使设置为自动换行也按一行匹配。</p>
</li>
<li><p>search</p>
<figure class="highlight python"><table><tbody><tr><td class="code"><pre class=" language-hljs python"><span class="hljs-keyword">import</span> re<br>strs=<span class="hljs-string">"i have a 98k. other all name it ojbk-.i haven't named it ojbk+.and it have a brother awm.it is a good gun."</span><br>regular_express_b = <span class="hljs-string">r"(awm|ojbk)[-|+]"</span><br>result = re.search(regular_express_b, strs)<br><span class="hljs-keyword">if</span> result!=<span class="hljs-literal">None</span>:<br>    <span class="hljs-built_in">print</span>(result)<br>    <span class="hljs-built_in"><code class="language-hljs python"><span class="hljs-keyword">import</span> re<br>strs=<span class="hljs-string">"i have a 98k. other all name it ojbk-.i haven't named it ojbk+.and it have a brother awm.it is a good gun."</span><br>regular_express_b = <span class="hljs-string">r"(awm|ojbk)[-|+]"</span><br>result = re.search(regular_express_b, strs)<br><span class="hljs-keyword">if</span> result!=<span class="hljs-literal">None</span>:<br>    <span class="hljs-built_in">print</span>(result)<br>    <span class="hljs-built_in">print</span>(result.start(),result.end(),result.group(),result.groups())<br><br></code></pre></td></tr></tbody></table></figure>

<blockquote>
<p>返回一个类，详细内容，可取官网查看。</p>
</blockquote>
<ul>
<li>官方文档：<a target="_blank" rel="noopener" href="https://docs.python.org/zh-cn/3/library/re.html">正则表达式操作 </a>：</li>
</ul>
</li>
<li><p>findall</p>
<figure class="highlight python"><table><tbody><tr><td class="code"><pre class=" language-hljs python"><span class="hljs-keyword">import</span> re<br>strs=<span class="hljs-string">"i have a 98k. other all name it ojbk-.i haven't named it ojbk+.and it have a brother awm.it is a good gun."</span><br>regular_express_b = <span class="hljs-string">r"(awm|ojbk)[-|+]"</span><br>result = re.findall(regular_express_b, strs)<br><span class="hljs-keyword">if</span> result!=<span class="hljs-literal">None</span>:<br>    <span class="hljs-built_in"><code class="language-hljs python"><span class="hljs-keyword">import</span> re<br>strs=<span class="hljs-string">"i have a 98k. other all name it ojbk-.i haven't named it ojbk+.and it have a brother awm.it is a good gun."</span><br>regular_express_b = <span class="hljs-string">r"(awm|ojbk)[-|+]"</span><br>result = re.findall(regular_express_b, strs)<br><span class="hljs-keyword">if</span> result!=<span class="hljs-literal">None</span>:<br>    <span class="hljs-built_in">print</span>(result)<br></code></pre></td></tr></tbody></table></figure>

<blockquote>
<p>返回所有匹配到的结果，以列表形式。</p>
</blockquote>
</li>
</ul>
<h3 id="5-2-替换"><a href="#5-2-替换" class="headerlink" title="5.2 替换"></a>5.2 替换</h3><p>re.sub(pattern,string)</p>
<figure class="highlight python"><table><tbody><tr><td class="code"><pre class=" language-hljs python"><span class="hljs-keyword">import</span> re<br>string = <span class="hljs-string">"蒹葭苍苍，白露为霜。所谓伊人，在水一方。溯洄从之，道阻且长。溯游从之，宛在水中央。\n蒹葭萋萋，白露未晞。所谓伊人，在水之湄。溯洄从之，道阻且跻。溯游从之，宛在水中坻。\n蒹葭采采，白露未已。所谓伊人，在水之涘。溯洄从之，道阻且右。溯游从之，宛在水中沚。\n"</span><br>letters = <span class="hljs-string">"     Transportation has been greatly changed in the past few years. In ancient days, people used to travel by horse or carriage. The journey was often tiring and tedious. Then people had buses, trains and ships, which could shorten the time of the long-distance trip."</span><br>regular_express = [<span class="hljs-string">r"(蒹葭|伊人)"</span>, <span class="hljs-string">r"(en|in|an)"</span>]<br><br><span class="hljs-built_in">print</span>(re.sub(regular_express[<span class="hljs-number">0</span>], <span class="hljs-string">"xx"</span>, string))<br><span class="hljs-built_in">print</span>(re.sub(regular_express[<span class="hljs-number">1</span>], <span class="hljs-string"><code class="language-hljs python"><span class="hljs-keyword">import</span> re<br>string = <span class="hljs-string">"蒹葭苍苍，白露为霜。所谓伊人，在水一方。溯洄从之，道阻且长。溯游从之，宛在水中央。\n蒹葭萋萋，白露未晞。所谓伊人，在水之湄。溯洄从之，道阻且跻。溯游从之，宛在水中坻。\n蒹葭采采，白露未已。所谓伊人，在水之涘。溯洄从之，道阻且右。溯游从之，宛在水中沚。\n"</span><br>letters = <span class="hljs-string">"     Transportation has been greatly changed in the past few years. In ancient days, people used to travel by horse or carriage. The journey was often tiring and tedious. Then people had buses, trains and ships, which could shorten the time of the long-distance trip."</span><br>regular_express = [<span class="hljs-string">r"(蒹葭|伊人)"</span>, <span class="hljs-string">r"(en|in|an)"</span>]<br><br><span class="hljs-built_in">print</span>(re.sub(regular_express[<span class="hljs-number">0</span>], <span class="hljs-string">"xx"</span>, string))<br><span class="hljs-built_in">print</span>(re.sub(regular_express[<span class="hljs-number">1</span>], <span class="hljs-string">" --XXXn-- "</span>, letters))<br></code></pre></td></tr></tbody></table></figure>



<h3 id="5-3-分割"><a href="#5-3-分割" class="headerlink" title="5.3 分割"></a>5.3 分割</h3><p>re.split(pattern,string)</p>
<figure class="highlight python"><table><tbody><tr><td class="code"><pre class=" language-hljs python"><span class="hljs-keyword">import</span> re<br>names = <span class="hljs-string">"焦英武、杨清双、吕纪领、张建春、焦灵卫、赵现伟\n陈秀荣、郎波、程磊、刘子祥、谢绍明 胡红军、张克龙、戴怀海 戴怀敏、张国勤\n李小璇、李军耐、张文博、赵联、肖鹏、边宪武、李伟、李宇、夏廷堂、韩世民、董燕平、张正银\n魏国琼、肖桂茂、李德安、白建永、张旭贵、李香明\n霍建辉、吴旭峰、陈云祥、丁连奇、王遂现、范小锋\n杨宗兵、向书章、李金民、戴家元、刘传禄、贺炳强、云秀芳\n刘善刚、姚海军、贾天义、李加有、方承、杨涛\n杨天海、王富军、张中华、王成林、秦振贵、尚鲜军、李友强、尚加聪"</span><br>pattern = <span class="hljs-string">r"( |、|\n)"</span><br><br>tup = re.split(pattern, names)<br><span class="hljs-keyword">for</span> index, item <span class="hljs-keyword">in</span> <span class="hljs-built_in">enumerate</span>(tup):<br>    <span class="hljs-keyword">if</span> index % <span class="hljs-number">2</span> == <span class="hljs-number">0</span>:<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">"第"</span>, <span class="hljs-built_in">int</span>(index / <span class="hljs-number">2</span>), <span class="hljs-string"><code class="language-hljs python"><span class="hljs-keyword">import</span> re<br>names = <span class="hljs-string">"焦英武、杨清双、吕纪领、张建春、焦灵卫、赵现伟\n陈秀荣、郎波、程磊、刘子祥、谢绍明 胡红军、张克龙、戴怀海 戴怀敏、张国勤\n李小璇、李军耐、张文博、赵联、肖鹏、边宪武、李伟、李宇、夏廷堂、韩世民、董燕平、张正银\n魏国琼、肖桂茂、李德安、白建永、张旭贵、李香明\n霍建辉、吴旭峰、陈云祥、丁连奇、王遂现、范小锋\n杨宗兵、向书章、李金民、戴家元、刘传禄、贺炳强、云秀芳\n刘善刚、姚海军、贾天义、李加有、方承、杨涛\n杨天海、王富军、张中华、王成林、秦振贵、尚鲜军、李友强、尚加聪"</span><br>pattern = <span class="hljs-string">r"( |、|\n)"</span><br><br>tup = re.split(pattern, names)<br><span class="hljs-keyword">for</span> index, item <span class="hljs-keyword">in</span> <span class="hljs-built_in">enumerate</span>(tup):<br>    <span class="hljs-keyword">if</span> index % <span class="hljs-number">2</span> == <span class="hljs-number">0</span>:<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">"第"</span>, <span class="hljs-built_in">int</span>(index / <span class="hljs-number">2</span>), <span class="hljs-string">"项："</span>, item)<br></code></pre></td></tr></tbody></table></figure>

<p>参考 </p>
<ul>
<li>官方文档：<a target="_blank" rel="noopener" href="https://docs.python.org/zh-cn/3/library/re.html">正则表达式操作 </a>：</li>
</ul>
<h2 id="6-函数"><a href="#6-函数" class="headerlink" title="6. 函数"></a>6. 函数</h2><h3 id="6-1普通函数"><a href="#6-1普通函数" class="headerlink" title="6.1普通函数"></a>6.1普通函数</h3><p>函数第一行为描述，在多数IDE中进行函数引用时，可显示。</p>
<figure class="highlight python"><table><tbody><tr><td class="code"><pre class=" language-hljs python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">reckon</span>(<span class="hljs-params">x,y</span>):</span><br>    <span class="hljs-string">"""求长方形面积 x: 长，y: 宽."""</span><br>    <span class="hljs-built_in">print</span>(<br>        <span class="hljs-string">"""{str1:{space}&gt;7s}={length:&gt;5d} \n{str2:{space}&gt;7s}={width:&gt;5d} \n{str3:{space}&gt;7s}={squr:&gt;5d} \n"""</span>.<span class="hljs-built_in">format</span>(<br>            str1=<span class="hljs-string">"此长方形长"</span>,<br>            str2=<span class="hljs-string">"此长方形宽"</span>,<br>            str3=<span class="hljs-string">"此正方形面积"</span>,<br>            length=x,<br>            width=y,<br>            squr=x * y,<br>            space=<span class="hljs-built_in">chr</span>(<span class="hljs-number">12288</span>),<br>        )<br>    )<br>    <br>reckon(<span class="hljs-built_in">int</span>(<span class="hljs-built_in">input</span>(<span class="hljs-string">"请输入长"</span>)) ,<span class="hljs-built_in">int</span>(<span class="hljs-built_in">input</span>(<span class="hljs-string"><code class="language-hljs python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">reckon</span>(<span class="hljs-params">x,y</span>):</span><br>    <span class="hljs-string">"""求长方形面积 x: 长，y: 宽."""</span><br>    <span class="hljs-built_in">print</span>(<br>        <span class="hljs-string">"""{str1:{space}&gt;7s}={length:&gt;5d} \n{str2:{space}&gt;7s}={width:&gt;5d} \n{str3:{space}&gt;7s}={squr:&gt;5d} \n"""</span>.<span class="hljs-built_in">format</span>(<br>            str1=<span class="hljs-string">"此长方形长"</span>,<br>            str2=<span class="hljs-string">"此长方形宽"</span>,<br>            str3=<span class="hljs-string">"此正方形面积"</span>,<br>            length=x,<br>            width=y,<br>            squr=x * y,<br>            space=<span class="hljs-built_in">chr</span>(<span class="hljs-number">12288</span>),<br>        )<br>    )<br>    <br>reckon(<span class="hljs-built_in">int</span>(<span class="hljs-built_in">input</span>(<span class="hljs-string">"请输入长"</span>)) ,<span class="hljs-built_in">int</span>(<span class="hljs-built_in">input</span>(<span class="hljs-string">"请输入宽"</span>)))<br></code></pre></td></tr></tbody></table></figure>



<h3 id="6-2-函数默认值"><a href="#6-2-函数默认值" class="headerlink" title="6.2 函数默认值"></a>6.2 函数默认值</h3><p> 当函数中出现有默认值时必须位于参数集的最后</p>
<figure class="highlight python"><table><tbody><tr><td class="code"><pre class=" language-hljs python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">R_S</span>(<span class="hljs-params">R, pai=<span class="hljs-number">3.14</span>, string=<span class="hljs-string">""</span></span>):</span><br>  <span class="hljs-string">"""圆求面积"""</span><br>  <span class="hljs-built_in">print</span>(<br>    <span class="hljs-string">"\n\n"</span>, string, <span class="hljs-string">"\n"</span>, <span class="hljs-string">"此圆的半径 r={radius: 5d}\n此圆的面积 S= {squr:.3f}"</span>.<span class="hljs-built_in">format</span>(<br>      radius=R, squr=R * R * pai ))<br><br>x = <span class="hljs-built_in">int</span>(<span class="hljs-built_in">input</span>(<span class="hljs-string">"输入圆的半径"</span>))<br>R_S(x, string=<span class="hljs-string">"R_S(x):"</span>)<br>R_S(x, <span class="hljs-number">3</span>, <span class="hljs-string">"R_S(x, 3):"</span>)<br>R_S(string=<span class="hljs-string">"R_S(pai=3.142, R=x):"</span>, pai=<span class="hljs-number"><code class="language-hljs python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">R_S</span>(<span class="hljs-params">R, pai=<span class="hljs-number">3.14</span>, string=<span class="hljs-string">""</span></span>):</span><br>  <span class="hljs-string">"""圆求面积"""</span><br>  <span class="hljs-built_in">print</span>(<br>    <span class="hljs-string">"\n\n"</span>, string, <span class="hljs-string">"\n"</span>, <span class="hljs-string">"此圆的半径 r={radius: 5d}\n此圆的面积 S= {squr:.3f}"</span>.<span class="hljs-built_in">format</span>(<br>      radius=R, squr=R * R * pai ))<br><br>x = <span class="hljs-built_in">int</span>(<span class="hljs-built_in">input</span>(<span class="hljs-string">"输入圆的半径"</span>))<br>R_S(x, string=<span class="hljs-string">"R_S(x):"</span>)<br>R_S(x, <span class="hljs-number">3</span>, <span class="hljs-string">"R_S(x, 3):"</span>)<br>R_S(string=<span class="hljs-string">"R_S(pai=3.142, R=x):"</span>, pai=<span class="hljs-number">3.142</span>, R=x)<br></code></pre></td></tr></tbody></table></figure>



<h3 id="6-3-匿名函数"><a href="#6-3-匿名函数" class="headerlink" title="6.3 匿名函数"></a>6.3 匿名函数</h3><p>临时函数，</p>
<figure class="highlight python"><table><tbody><tr><td class="code"><pre class=" language-hljs python"><span class="hljs-comment">#  匿名函数 用 lambda 修饰词前缀.</span><br>y = <span class="hljs-keyword">lambda</span> ds: ds * ds * <span class="hljs-number">3.14</span><br><span class="hljs-built_in">print</span>(<span class="hljs-string">"\n"</span> + <span class="hljs-built_in"><code class="language-hljs python"><span class="hljs-comment">#  匿名函数 用 lambda 修饰词前缀.</span><br>y = <span class="hljs-keyword">lambda</span> ds: ds * ds * <span class="hljs-number">3.14</span><br><span class="hljs-built_in">print</span>(<span class="hljs-string">"\n"</span> + <span class="hljs-built_in">str</span>(y(x)))<br></code></pre></td></tr></tbody></table></figure>



<p>匿名函数多参</p>
<figure class="highlight python"><table><tbody><tr><td class="code"><pre class=" language-hljs python"><span class="hljs-comment">#  传入数组，或多参数。</span><br><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">func</span>(<span class="hljs-params">*par</span>):</span><br>  <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> par:<br>    <span class="hljs-built_in">print</span>(i)<br>    <br><span class="hljs-comment">#  参数原理为：定义一个变量的列表，用*来传入列表地址</span><br><br>strs = [<span class="hljs-string">"语文"</span>, <span class="hljs-string">"数学"</span>, <span class="hljs-string">"英语"</span>, <span class="hljs-string">"物理"</span>, <span class="hljs-string">"化学"</span>]<br>strss = [<span class="hljs-string">"Chinese"</span>, [<span class="hljs-number">12.0</span>, <span class="hljs-number">45.12</span>, <span class="hljs-number">44.11</span>], <span class="hljs-number">45699</span>, <span class="hljs-built_in">bin</span>(<span class="hljs-number">423</span>),<span class="hljs-built_in">hex</span>(<span class="hljs-number">423</span>)]<br>func(*strs)<br><span class="hljs-built_in">print</span>(<span class="hljs-string"><code class="language-hljs python"><span class="hljs-comment">#  传入数组，或多参数。</span><br><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">func</span>(<span class="hljs-params">*par</span>):</span><br>  <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> par:<br>    <span class="hljs-built_in">print</span>(i)<br>    <br><span class="hljs-comment">#  参数原理为：定义一个变量的列表，用*来传入列表地址</span><br><br>strs = [<span class="hljs-string">"语文"</span>, <span class="hljs-string">"数学"</span>, <span class="hljs-string">"英语"</span>, <span class="hljs-string">"物理"</span>, <span class="hljs-string">"化学"</span>]<br>strss = [<span class="hljs-string">"Chinese"</span>, [<span class="hljs-number">12.0</span>, <span class="hljs-number">45.12</span>, <span class="hljs-number">44.11</span>], <span class="hljs-number">45699</span>, <span class="hljs-built_in">bin</span>(<span class="hljs-number">423</span>),<span class="hljs-built_in">hex</span>(<span class="hljs-number">423</span>)]<br>func(*strs)<br><span class="hljs-built_in">print</span>(<span class="hljs-string">"\n"</span>)<br>func(*strss)<br></code></pre></td></tr></tbody></table></figure>



<h2 id="7-python数据存储原理"><a href="#7-python数据存储原理" class="headerlink" title="7. python数据存储原理"></a>7. python数据存储原理</h2><blockquote>
<p>返回对象的“标识值”。该值是一个整数，在此对象的生命周期中保证是唯一且恒定的。两个生命期不重叠的对象可能具有相同的 <a target="_blank" rel="noopener" href="https://docs.python.org/zh-cn/3/library/functions.html?highlight=id#id"><code>id()</code></a> 值。</p>
</blockquote>
<p>以上为官方关于 id () 函数的解释。一般来说，在其他语言中，变量名地址生命周期内唯一确定不变，对应地址存储的数值可变。但 <code>python </code> 却是变量的值决定地址。</p>
<figure class="highlight python"><table><tbody><tr><td class="code"><pre class=" language-hljs python">x=<span class="hljs-string">"x"</span><br><span class="hljs-built_in">print</span>(<span class="hljs-built_in">id</span>(<span class="hljs-string">"x"</span>))<br><span class="hljs-built_in">print</span>(<span class="hljs-built_in"><code class="language-hljs python">x=<span class="hljs-string">"x"</span><br><span class="hljs-built_in">print</span>(<span class="hljs-built_in">id</span>(<span class="hljs-string">"x"</span>))<br><span class="hljs-built_in">print</span>(<span class="hljs-built_in">id</span>(x))<br></code></pre></td></tr></tbody></table></figure>

<p>以上代码将会输出同样的值。主要是因为 python 中对<code>对象</code>这一概念的执著。他把每一个数值也视为对象。当你声明一个变量并赋值时，首先python编译器做的是申请内存存储赋的值，然后把这一变量指向这一内存。所以不同的值对应不同的地址。</p>
<blockquote>
<p>当赋的值为简单数据类型时，python不会再申请，而是先查找是否申请过，如果申请过，则直接指向这块内存。否则再申请。<br>        复杂数据类型，则不进行检查。因为怕你一个数组存了全个国家的名字，然后接下来几个变量又来赋值，如果检查，那CPU不是要抽两口烟了。</p>
</blockquote>
<p>参考： </p>
<ul>
<li><a target="_blank" rel="noopener" href="https://blog.csdn.net/zhuzuwei/article/details/80554776">python id()函数和内存分配理解</a></li>
<li><a target="_blank" rel="noopener" href="https://blog.csdn.net/tycoon1988/article/details/38850443">Python id() 函数</a></li>
</ul>
<h2 id="8-class"><a href="#8-class" class="headerlink" title="8. class"></a>8. class</h2><figure class="highlight python"><table><tbody><tr><td class="code"><pre class=" language-hljs python"><span class="hljs-comment">#  keyword：“class”，“从序列中取随机元素”，“从字典中取随机元素”</span><br><span class="hljs-comment">#           “choice”，</span><br><br><span class="hljs-comment"># encoding:utf-8</span><br><br>brand = {<span class="hljs-string">"上汽集团"</span>: <span class="hljs-string">"大众"</span>, <span class="hljs-string">"东风"</span>: <span class="hljs-string">"雪铁龙"</span>, <span class="hljs-string">"奔驰"</span>: <span class="hljs-string">"Mercedes-Benz"</span>, <span class="hljs-string">"凯迪拉克"</span>: <span class="hljs-string">"Cadillac"</span>}<br>produce_country = [<span class="hljs-string">"China"</span>, <span class="hljs-string">"American"</span>, <span class="hljs-string">"India"</span>, <span class="hljs-string">"European"</span>]<br>code = <span class="hljs-string">"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"</span><br><span class="hljs-comment"># -----------------class----------------&gt;#</span><br><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Car</span>:</span><br>  <span class="hljs-string">""" 汽车模型 先生成后赋值 """</span><br>  Name = <span class="hljs-string">""</span><br>  Brand = <span class="hljs-string">""</span><br>  Producer = <span class="hljs-string">""</span><br>  Produce_Country = <span class="hljs-string">""</span><br>  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">make_success</span>(<span class="hljs-params">self</span>):</span><br>    <span class="hljs-built_in">print</span>(<br>      <span class="hljs-string">"生成了一辆小汽车"</span>,<br>      <span class="hljs-string">"\n名字:"</span> + self.Name,<br>      <span class="hljs-string">"\n品牌:"</span> + self.Brand,<br>      <span class="hljs-string">"\n生产商:"</span> + self.Producer,<br>      <span class="hljs-string">"\n产地:"</span> + self.Produce_Country,<br>      <span class="hljs-string">"\n"</span>,<br>    )<br><span class="hljs-comment"># 一个类中同一方法只能生效最后一次定义。</span><br><span class="hljs-string">""" 初始化函数与构造函数 括号内不加参数时函数内</span><br><span class="hljs-string">   def __init__():</span><br><span class="hljs-string">     brand = self.carname</span><br><span class="hljs-string">   print("生成了一辆小汽车:222")</span><br><span class="hljs-string"> """</span><br><span class="hljs-comment"># -------------------function-----------------------&lt;#</span><br>	<span class="hljs-comment">#-----------------class-----------------&gt;#</span><br><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">mass_produce</span>(<span class="hljs-params">number</span>):</span><br>  <span class="hljs-string">""" 批量造车 """</span><br>  <span class="hljs-keyword">import</span> random<br>  lis = []<br>  i = <span class="hljs-number">0</span><br>  <span class="hljs-keyword">while</span> i &lt; number:<br>    i = i + <span class="hljs-number">1</span><br>    j = <span class="hljs-number">0</span><br>    name = <span class="hljs-string">""</span><br>    <span class="hljs-keyword">while</span> j &lt;= <span class="hljs-number">10</span>:<br>      name += code[random.randint(<span class="hljs-number">0</span>, <span class="hljs-built_in">len</span>(code) - <span class="hljs-number">1</span>)]<br>      j = j + <span class="hljs-number">1</span><br>    car = Car()<br>    car.Name = name<br>    car.Brand = random.choice((<span class="hljs-built_in">list</span>(brand)))<br>    car.Produce_Country = random.choice(produce_country)<br>    car.Producer = brand[car.Brand]<br>    lis.append(car)<br>  <span class="hljs-keyword">return</span> lis<br><span class="hljs-comment"># ---------------------function----------------------&lt;#</span><br>numb = <span class="hljs-built_in">int</span>(<span class="hljs-built_in">input</span>(<span class="hljs-string">"输入生产汽车的数量"</span>))<br>t = mass_produce(numb)<br><span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> t:<br>  i.make_success()<br><span class="hljs-built_in">print</span>(<span class="hljs-string">"已成功生产"</span>, numb, <span class="hljs-string"><code class="language-hljs python"><span class="hljs-comment">#  keyword：“class”，“从序列中取随机元素”，“从字典中取随机元素”</span><br><span class="hljs-comment">#           “choice”，</span><br><br><span class="hljs-comment"># encoding:utf-8</span><br><br>brand = {<span class="hljs-string">"上汽集团"</span>: <span class="hljs-string">"大众"</span>, <span class="hljs-string">"东风"</span>: <span class="hljs-string">"雪铁龙"</span>, <span class="hljs-string">"奔驰"</span>: <span class="hljs-string">"Mercedes-Benz"</span>, <span class="hljs-string">"凯迪拉克"</span>: <span class="hljs-string">"Cadillac"</span>}<br>produce_country = [<span class="hljs-string">"China"</span>, <span class="hljs-string">"American"</span>, <span class="hljs-string">"India"</span>, <span class="hljs-string">"European"</span>]<br>code = <span class="hljs-string">"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"</span><br><span class="hljs-comment"># -----------------class----------------&gt;#</span><br><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Car</span>:</span><br>  <span class="hljs-string">""" 汽车模型 先生成后赋值 """</span><br>  Name = <span class="hljs-string">""</span><br>  Brand = <span class="hljs-string">""</span><br>  Producer = <span class="hljs-string">""</span><br>  Produce_Country = <span class="hljs-string">""</span><br>  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">make_success</span>(<span class="hljs-params">self</span>):</span><br>    <span class="hljs-built_in">print</span>(<br>      <span class="hljs-string">"生成了一辆小汽车"</span>,<br>      <span class="hljs-string">"\n名字:"</span> + self.Name,<br>      <span class="hljs-string">"\n品牌:"</span> + self.Brand,<br>      <span class="hljs-string">"\n生产商:"</span> + self.Producer,<br>      <span class="hljs-string">"\n产地:"</span> + self.Produce_Country,<br>      <span class="hljs-string">"\n"</span>,<br>    )<br><span class="hljs-comment"># 一个类中同一方法只能生效最后一次定义。</span><br><span class="hljs-string">""" 初始化函数与构造函数 括号内不加参数时函数内</span><br><span class="hljs-string">   def __init__():</span><br><span class="hljs-string">     brand = self.carname</span><br><span class="hljs-string">   print("生成了一辆小汽车:222")</span><br><span class="hljs-string"> """</span><br><span class="hljs-comment"># -------------------function-----------------------&lt;#</span><br>	<span class="hljs-comment">#-----------------class-----------------&gt;#</span><br><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">mass_produce</span>(<span class="hljs-params">number</span>):</span><br>  <span class="hljs-string">""" 批量造车 """</span><br>  <span class="hljs-keyword">import</span> random<br>  lis = []<br>  i = <span class="hljs-number">0</span><br>  <span class="hljs-keyword">while</span> i &lt; number:<br>    i = i + <span class="hljs-number">1</span><br>    j = <span class="hljs-number">0</span><br>    name = <span class="hljs-string">""</span><br>    <span class="hljs-keyword">while</span> j &lt;= <span class="hljs-number">10</span>:<br>      name += code[random.randint(<span class="hljs-number">0</span>, <span class="hljs-built_in">len</span>(code) - <span class="hljs-number">1</span>)]<br>      j = j + <span class="hljs-number">1</span><br>    car = Car()<br>    car.Name = name<br>    car.Brand = random.choice((<span class="hljs-built_in">list</span>(brand)))<br>    car.Produce_Country = random.choice(produce_country)<br>    car.Producer = brand[car.Brand]<br>    lis.append(car)<br>  <span class="hljs-keyword">return</span> lis<br><span class="hljs-comment"># ---------------------function----------------------&lt;#</span><br>numb = <span class="hljs-built_in">int</span>(<span class="hljs-built_in">input</span>(<span class="hljs-string">"输入生产汽车的数量"</span>))<br>t = mass_produce(numb)<br><span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> t:<br>  i.make_success()<br><span class="hljs-built_in">print</span>(<span class="hljs-string">"已成功生产"</span>, numb, <span class="hljs-string">"辆车"</span>)<br></code></pre></td></tr></tbody></table></figure>



<h2 id="9-访问限制"><a href="#9-访问限制" class="headerlink" title="9. 访问限制"></a>9. 访问限制</h2><figure class="highlight python"><table><tbody><tr><td class="code"><pre class=" language-hljs python"><span class="hljs-comment">#  keyword：“访问限制”，</span><br><span class="hljs-comment">#  没多大用。。。。。。。</span><br><br><span class="hljs-comment"># encoding:utf-8</span><br><br><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">car</span>:</span><br>  <span class="hljs-string">""" produce car """</span><br><span class="hljs-comment"># price: ""</span><br><span class="hljs-comment"># _brand: ""</span><br><span class="hljs-comment"># __color: ""</span><br>  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self</span>):</span><br>    self.price = <span class="hljs-number">4000</span><br>    self._brand = <span class="hljs-string">"asdfa"</span><br>    self.__color = <span class="hljs-string">"red"</span><br>vehicle = car()<br><span class="hljs-built_in">print</span>(vehicle.price)<br><span class="hljs-built_in">print</span>(vehicle._brand)<br><span class="hljs-built_in">print</span>(vehicle._car__color)<br>vehicle.price = <span class="hljs-number">50</span><br>vehicle._brand = <span class="hljs-string">"qqqqqqqqqqq"</span><br>vehicle._car__color = <span class="hljs-string">"aaaaaaaaaa"</span><br><span class="hljs-built_in">print</span>(vehicle.price)<br><span class="hljs-built_in">print</span>(vehicle._brand)<br><span class="hljs-built_in"><code class="language-hljs python"><span class="hljs-comment">#  keyword：“访问限制”，</span><br><span class="hljs-comment">#  没多大用。。。。。。。</span><br><br><span class="hljs-comment"># encoding:utf-8</span><br><br><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">car</span>:</span><br>  <span class="hljs-string">""" produce car """</span><br><span class="hljs-comment"># price: ""</span><br><span class="hljs-comment"># _brand: ""</span><br><span class="hljs-comment"># __color: ""</span><br>  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self</span>):</span><br>    self.price = <span class="hljs-number">4000</span><br>    self._brand = <span class="hljs-string">"asdfa"</span><br>    self.__color = <span class="hljs-string">"red"</span><br>vehicle = car()<br><span class="hljs-built_in">print</span>(vehicle.price)<br><span class="hljs-built_in">print</span>(vehicle._brand)<br><span class="hljs-built_in">print</span>(vehicle._car__color)<br>vehicle.price = <span class="hljs-number">50</span><br>vehicle._brand = <span class="hljs-string">"qqqqqqqqqqq"</span><br>vehicle._car__color = <span class="hljs-string">"aaaaaaaaaa"</span><br><span class="hljs-built_in">print</span>(vehicle.price)<br><span class="hljs-built_in">print</span>(vehicle._brand)<br><span class="hljs-built_in">print</span>(vehicle._car__color)<br></code></pre></td></tr></tbody></table></figure>

<h2 id="10-property"><a href="#10-property" class="headerlink" title="10. property"></a>10. property</h2><figure class="highlight python"><table><tbody><tr><td class="code"><pre class=" language-hljs python"><span class="hljs-comment">#  keyword：“属性变化”，“装饰器”，“property”</span><br><br><span class="hljs-comment"># encoding:utf-8</span><br><br><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">car</span>:</span><br>  <span class="hljs-string">"""计算价格"""</span><br>  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, door, tie</span>):</span><br>    self.door = door<br>    self.tie = tie<br>    self.band_price = <span class="hljs-number">5000.0</span><br><span class="hljs-comment">#  方法转换为属性</span><br><span class="hljs-meta">  @property</span><br>  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">total_cost</span>(<span class="hljs-params">self</span>):</span><br>    <span class="hljs-string">"""(door + tie) x 4 + price"""</span><br>    <span class="hljs-keyword">return</span> (self.door + self.tie) * <span class="hljs-number">4</span> + self.band_price<br>spend = car(<span class="hljs-number">203</span>, <span class="hljs-number">450</span>)<br><span class="hljs-built_in"><code class="language-hljs python"><span class="hljs-comment">#  keyword：“属性变化”，“装饰器”，“property”</span><br><br><span class="hljs-comment"># encoding:utf-8</span><br><br><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">car</span>:</span><br>  <span class="hljs-string">"""计算价格"""</span><br>  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, door, tie</span>):</span><br>    self.door = door<br>    self.tie = tie<br>    self.band_price = <span class="hljs-number">5000.0</span><br><span class="hljs-comment">#  方法转换为属性</span><br><span class="hljs-meta">  @property</span><br>  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">total_cost</span>(<span class="hljs-params">self</span>):</span><br>    <span class="hljs-string">"""(door + tie) x 4 + price"""</span><br>    <span class="hljs-keyword">return</span> (self.door + self.tie) * <span class="hljs-number">4</span> + self.band_price<br>spend = car(<span class="hljs-number">203</span>, <span class="hljs-number">450</span>)<br><span class="hljs-built_in">print</span>(spend.total_cost)<br></code></pre></td></tr></tbody></table></figure>

<h2 id="11-文件操作—-IO"><a href="#11-文件操作—-IO" class="headerlink" title="11. 文件操作—-IO"></a>11. 文件操作—-IO</h2><p>流程为先打开一个文件 （程序中的一个对象），然后对这个对象进行操作。</p>
<h3 id="11-1-打开"><a href="#11-1-打开" class="headerlink" title="11.1 打开"></a>11.1 打开</h3><p>通过open方法打开一个文件。对于文件是否存在通过方法的参数指定打开方式。</p>
<figure class="highlight python"><table><tbody><tr><td class="code"><pre class=" language-hljs python">file=<span class="hljs-built_in">open</span>(file, mode,buffering=<span class="hljs-number">1</span>,encoding=<span class="hljs-string"><code class="language-hljs python">file=<span class="hljs-built_in">open</span>(file, mode,buffering=<span class="hljs-number">1</span>,encoding=<span class="hljs-string">"utf-8"</span>)<br>file.close()<br></code></pre></td></tr></tbody></table></figure>

<blockquote>
<p>一定要记得关闭，否则如果是写操作，未关闭则不会写入。如果是读，会一直占用此文件。其他对于此文件的读写操作会被影响，比如删除时会提示文件被占用，无法删除。</p>
</blockquote>
<blockquote>
<ul>
<li>file 文件路径。可以使用相对路径或者绝对路径。</li>
<li>mode 文件打开模式。值为以下表所示。</li>
<li>buffering 指定文件是否进行缓存。</li>
<li>encoding=“utf-8” 指定此编码格式打开，默认为 GBK格式 打开</li>
</ul>
<p>mode 值为以下几种值或者他们的组合。</p>
</blockquote>
<p>参数如下。</p>
<table>
<thead>
<tr>
<th align="center">参数值</th>
<th align="left">含义</th>
<th>可组合项</th>
</tr>
</thead>
<tbody><tr>
<td align="center">w</td>
<td align="left">指定为写打开。文件存在就覆盖，不存在就创建</td>
<td>~ +，~ b，~ b+</td>
</tr>
<tr>
<td align="center">r</td>
<td align="left">指定为只读打开，文件必须已存在。打开后指针在文件开头。</td>
<td>同上</td>
</tr>
<tr>
<td align="center">+</td>
<td align="left">扩展 r、w 权限，使 r 可写（从文件头开始覆盖写），使 w 可读（先覆盖，后读写）。</td>
<td></td>
</tr>
<tr>
<td align="center">a</td>
<td align="left">以追加形式打开文件操作，打开后指针在文件末尾。</td>
<td>~ +（读写），~ b<br>，~ b+</td>
</tr>
<tr>
<td align="center">b</td>
<td align="left">以二进制的形式进行文件读写。一般用于非文本文件。</td>
<td></td>
</tr>
</tbody></table>
<h3 id="11-2-write"><a href="#11-2-write" class="headerlink" title="11.2 write"></a>11.2 write</h3><p><code>file.write(string)</code></p>
<p>向file中写入<code>string</code>字符串。</p>
<blockquote>
<p>必须以 <code>w</code>及<code>w组合</code> 或者 <code>a</code>及<code>a组合</code> 打开，否则会报错。</p>
</blockquote>
<figure class="highlight python"><table><tbody><tr><td class="code"><pre class=" language-hljs python">wf=<span class="hljs-built_in">open</span>(<span class="hljs-string">"./demo.txt"</span>,<span class="hljs-string">"+w"</span>)<br>wf.write(<span class="hljs-string"><code class="language-hljs python">wf=<span class="hljs-built_in">open</span>(<span class="hljs-string">"./demo.txt"</span>,<span class="hljs-string">"+w"</span>)<br>wf.write(<span class="hljs-string">"sdnakjldnvn435746954u83o2abc123"</span>)<br>wf.close()<br></code></pre></td></tr></tbody></table></figure>



<h3 id="11-2-read"><a href="#11-2-read" class="headerlink" title="11.2 read"></a>11.2 read</h3><p><code>file.read(size)</code></p>
<p>从file中读取字符串。</p>
<blockquote>
<p>size 读取的数据长度。实际指读取指针的移动距离。未指定为完全读取。</p>
<p>再次使用read会接着上次的位置继续读取。</p>
</blockquote>
<p><code>file.seek(offset[,whence])</code> </p>
<p>指针从whence指定位置开始往后移动offset个字符。</p>
<blockquote>
<p>offset 移动的字符长度</p>
<p>whence 开始的位置，默认为0。0为开头，1为当前位置，2为末尾。如果打开方式不是 <code>rb</code> ，则强制为0。</p>
</blockquote>
<p><code>text=file.readline()</code> </p>
<p>读取一行内容。</p>
<p><code>texts=file.readlines()</code> </p>
<p>读取全部行。返回一个列表。行号为索引。</p>
<figure class="highlight python"><table><tbody><tr><td class="code"><pre class=" language-hljs python">rf=<span class="hljs-built_in">open</span>(<span class="hljs-string">"./demo.txt"</span>,<span class="hljs-string"><code class="language-hljs python">rf=<span class="hljs-built_in">open</span>(<span class="hljs-string">"./demo.txt"</span>,<span class="hljs-string">"r"</span>)<br>rf.readline()<br></code></pre></td></tr></tbody></table></figure>



<h3 id="11-3-代码示例"><a href="#11-3-代码示例" class="headerlink" title="11.3 代码示例"></a>11.3 代码示例</h3><p>以下代码为创建demo.txt文件，然后写入 <code>....</code> ，再然后读取、输出。</p>
<figure class="highlight python"><table><tbody><tr><td class="code"><pre class=" language-hljs python">wf=<span class="hljs-built_in">open</span>(<span class="hljs-string">"./demo.txt"</span>,<span class="hljs-string">"+w"</span>)<br>wf.write(<span class="hljs-string">"sdnakjldnvn435746954u83o2abc123"</span>)<br>wf.close()<br>rf=<span class="hljs-built_in">open</span>(<span class="hljs-string">"./demo.txt"</span>,<span class="hljs-string">"r"</span>,buffering=<span class="hljs-number">1</span>)<br><span class="hljs-built_in">print</span>(rf.read(<span class="hljs-number">10</span>))<br><span class="hljs-built_in">print</span>(rf.read(<span class="hljs-number"><code class="language-hljs python">wf=<span class="hljs-built_in">open</span>(<span class="hljs-string">"./demo.txt"</span>,<span class="hljs-string">"+w"</span>)<br>wf.write(<span class="hljs-string">"sdnakjldnvn435746954u83o2abc123"</span>)<br>wf.close()<br>rf=<span class="hljs-built_in">open</span>(<span class="hljs-string">"./demo.txt"</span>,<span class="hljs-string">"r"</span>,buffering=<span class="hljs-number">1</span>)<br><span class="hljs-built_in">print</span>(rf.read(<span class="hljs-number">10</span>))<br><span class="hljs-built_in">print</span>(rf.read(<span class="hljs-number">10</span>))<br>rf.close()<br></code></pre></td></tr></tbody></table></figure>





<h2 id="12-OS-Path"><a href="#12-OS-Path" class="headerlink" title="12. OS - Path"></a>12. OS - Path</h2><p>引入模块<code>import os</code></p>
<ul>
<li><p>判断路径</p>
<p><code>os.path.exists(path)</code> </p>
<p>判断路径是否存在。返回bool值</p>
</li>
<li><p>创建路径</p>
<p><code>os.mkdir(path)</code></p>
<p>创建单级菜单。也就是指定路径的每一级，然后创建最后一层的文件夹。</p>
<blockquote>
<p>当最后一级前的部分有不存在的则会报错。所以建议结合<code>exists()</code></p>
</blockquote>
<p><code>os.makedirs(path)</code></p>
<p>创建多级菜单，同样指定路径的每一级，任意一级不存在就会创建，直至创建完最后一级。</p>
</li>
<li><p>删除路径</p>
<p><code>rmdir(path)</code> 删除指定路径，但前提是路径中没有文件。否则会报错。同样，路径不存在也会报错。</p>
<p>如果需要完全删除可使用下方代码</p>
<figure class="highlight python"><table><tbody><tr><td class="code"><pre class=" language-hljs python"><span class="hljs-keyword"><code class="language-hljs python"><span class="hljs-keyword">import</span> shutil<br>shutil.rmtree(path)<br></code></pre></td></tr></tbody></table></figure></li>
<li><p>遍历目录</p>
<p><code>os.walk(top,topdown,onerror,followlinks)</code> </p>
<ul>
<li><p>top 为遍历的路径。</p>
</li>
<li><p>topdown 布尔值，指定是否为从上到下遍历。默认为true。</p>
</li>
<li><p>onerror 遍历出现错误时的处理方式，默认为忽略。</p>
</li>
<li><p>followlinks ———……</p>
</li>
</ul>
<p>返回一个元组。</p>
<p>​       三个元素：dirpath，dirnanes，filenames。</p>
<ul>
<li>dirpath– 当前遍历路径。是一个字符串</li>
<li>dirnames– 遍历时的所有路径。是一个列表。</li>
<li>filenames– 遍历到的文件。是一个列表。</li>
</ul>
</li>
</ul>
<h3 id="12-5-删除文件"><a href="#12-5-删除文件" class="headerlink" title="12.5 删除文件"></a>12.5 删除文件</h3><h3 id="12-6-修改路径与文件名"><a href="#12-6-修改路径与文件名" class="headerlink" title="12.6 修改路径与文件名"></a>12.6 修改路径与文件名</h3><h3 id="12-7-获取文件信息"><a href="#12-7-获取文件信息" class="headerlink" title="12.7 获取文件信息"></a>12.7 获取文件信息</h3>
                
            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="/about" rel="external nofollow noreferrer">Zhang-little-white</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://blogofxyz.top/2021/08/21/python%E5%85%A5%E9%97%A8/">https://blogofxyz.top/2021/08/21/python%E5%85%A5%E9%97%A8/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="/about" target="_blank">Zhang-little-white</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/tags/Python/">
                                    <span class="chip bg-color">Python</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">
<div id="article-share">

    
    <div class="social-share" data-sites="qq,qzone,wechat,weibo" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    
    <script type="text/javascript" src="//s7.addthis.com/js/300/addthis_widget.js#pubid="></script>
    <div class="addthis_inline_share_toolbox"></div>
    

</div>

                </div>
            </div>
            
                <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.4rem;
        line-height: 38px;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/medias/reward/alipay.png" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/medias/reward/wechat.png" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>

            
        </div>
    </div>

    

    

    

    

    
        <style>
    .valine-card {
        margin: 1.5rem auto;
    }

    .valine-card .card-content {
        padding: 20px 20px 5px 20px;
    }

    #vcomments textarea {
        box-sizing: border-box;
        background: url("/medias/comment_bg.JPG") 100% 100% no-repeat;
	    color: white;
    opacity: 0.8;
    font-size: 18px;
    }

    #vcomments p {
        margin: 2px 2px 10px;
        font-size: 1.05rem;
        line-height: 1.78rem;
    }

    #vcomments blockquote p {
        text-indent: 0.2rem;
    }

    #vcomments a {
        padding: 0 2px;
        color: #4cbf30;
        font-weight: 500;
        text-decoration: none;
    }

    #vcomments img {
        max-width: 100%;
        height: auto;
        cursor: pointer;
    }

    #vcomments ol li {
        list-style-type: decimal;
    }

    #vcomments ol,
    ul {
        display: block;
        padding-left: 2em;
        word-spacing: 0.05rem;
    }

    #vcomments ul li,
    ol li {
	text-indent:2rem;
        display: list-item;
        line-height: 2.2rem;
        font-size: 1rem;
    }

    #vcomments ul li {
        list-style-type: disc;
    }

    #vcomments ul ul li {
        list-style-type: circle;
    }

    #vcomments table, th, td {
        padding: 12px 13px;
        border: 1px solid #dfe2e5;
    }

    #vcomments table, th, td {
        border: 0;
    }

    table tr:nth-child(2n), thead {
        background-color: #fafafa;
    }

    #vcomments table th {
        background-color: #f2f2f2;
        min-width: 80px;
    }

    #vcomments table td {
        min-width: 80px;
    }

    #vcomments h1 {
        font-size: 1.85rem;
        font-weight: bold;
        line-height: 2.2rem;
    }

    #vcomments h2 {
        font-size: 1.65rem;
        font-weight: bold;
        line-height: 1.9rem;
    }

    #vcomments h3 {
        font-size: 1.45rem;
        font-weight: bold;
        line-height: 1.7rem;
    }

    #vcomments h4 {
        font-size: 1.25rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    #vcomments h5 {
        font-size: 1.1rem;
        font-weight: bold;
        line-height: 1.4rem;
    }

    #vcomments h6 {
        font-size: 1rem;
        line-height: 1.3rem;
    }

    #vcomments p {
        font-size: 1rem;
        line-height: 1.5rem;
    }

    #vcomments hr {
        margin: 12px 0;
        border: 0;
        border-top: 1px solid #ccc;
    }

    #vcomments blockquote {
        margin: 15px 0;
        border-left: 5px solid #42b983;
        padding: 1rem 0.8rem 0.3rem 0.8rem;
        color: #666;
        background-color: rgba(66, 185, 131, .1);
    }

    #vcomments pre {
        font-family: monospace, monospace;
        padding: 1.2em;
        margin: .5em 0;
        background: #272822;
        overflow: auto;
        border-radius: 0.3em;
        tab-size: 4;
    }

    #vcomments code {
        font-family: monospace, monospace;
        padding: 1px 3px;
        font-size: 0.92rem;
        color: #e96900;
        background-color: #f8f8f8;
        border-radius: 2px;
    }

    #vcomments pre code {
        font-family: monospace, monospace;
        padding: 0;
        color: #e8eaf6;
        background-color: #272822;
    }

    #vcomments pre[class*="language-"] {
        padding: 1.2em;
        margin: .5em 0;
    }

    #vcomments code[class*="language-"],
    pre[class*="language-"] {
        color: #e8eaf6;
    }

    #vcomments [type="checkbox"]:not(:checked), [type="checkbox"]:checked {
        position: inherit;
        margin-left: -1.3rem;
        margin-right: 0.4rem;
        margin-top: -1px;
        vertical-align: middle;
        left: unset;
        visibility: visible;
    }

    #vcomments b,
    strong {
        font-weight: bold;
    }

    #vcomments dfn {
        font-style: italic;
    }

    #vcomments small {
        font-size: 85%;
    }

    #vcomments cite {
        font-style: normal;
    }

    #vcomments mark {
        background-color: #fcf8e3;
        padding: .2em;
    }

    #vcomments table, th, td {
        padding: 12px 13px;
        border: 1px solid #dfe2e5;
    }

    table tr:nth-child(2n), thead {
        background-color: #fafafa;
    }

    #vcomments table th {
        background-color: #f2f2f2;
        min-width: 80px;
    }

    #vcomments table td {
        min-width: 80px;
    }

    #vcomments [type="checkbox"]:not(:checked), [type="checkbox"]:checked {
        position: inherit;
        margin-left: -1.3rem;
        margin-right: 0.4rem;
        margin-top: -1px;
        vertical-align: middle;
        left: unset;
        visibility: visible;
    }
	.v[data-class="v"] .vwrap .vheader .vinput {
		width: 32%;
		border-bottom: 1px dashed #dedede;
	}
</style>

<div class="card valine-card" data-aos="fade-up">
    <div class="comment_headling" style="font-size: 20px; font-weight: 700; position: relative; padding-left: 20px; top: 15px; padding-bottom: 5px;">
        <i class="fas fa-comments fa-fw" aria-hidden="true"></i>
        <span>评论</span>
    </div>
    <div id="vcomments" class="card-content" style="display: grid">
    </div>
</div>

<script src="/libs/valine/av-min.js"></script>
<script src="/libs/valine/Valine.min.js"></script>
<script>
	let metaPlaceholder = {"nick":"昵称/QQ号(必填)","mail":"邮箱(必填)","link":"网址(https://)"} ;
	
	new Valine({
			el: '#vcomments',
			appId: 'ghConjcbp7CpCRHJFPIRDdd2-gzGzoHsz',
			appKey: 'XnhsRQe0DKrPj7X8NnqYg6BX',
			notify: 'true' === 'true',
			verify: 'true' === 'true',
			visitor: 'true' === 'true',
			avatar: 'identicon',
			pageSize: '10',
			lang: 'zh-CN',
			placeholder: '有事不怕打扰，如果较急，可使用右侧反馈快速接受。',
			meta: ["y-nick", "e-mail", "your-link"],
			recordIP: 'true' === 'true',
			enableQQ: 'identicon',
			requiredFields: ["721850218d5dfa3e2ad5b3ac5a69dad8"],
			master: ["721850218d5dfa3e2ad5b3ac5a69dad8"],
			friends: ["4802978b7156ffcf24b571b35c594ad7"],
			tagMeta: ["发文地", "认识地", "过路地"],
			metaPlaceholder: metaPlaceholder,
		});
</script>

<!--酷Q推送-->


    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/2021/08/23/c%E8%AF%AD%E8%A8%80&CMD/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/6.jpg" class="responsive-img" alt="c语言与cmd">
                        
                        <span class="card-title">c语言与cmd</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            用C语言启动一些程序，或者执行windows的一些操作。
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2021-08-23
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/C/" class="post-category">
                                    C
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/C%E8%AF%AD%E8%A8%80/">
                        <span class="chip bg-color">C语言</span>
                    </a>
                    
                    <a href="/tags/CMD/">
                        <span class="chip bg-color">CMD</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/2021/08/21/%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/6.jpg" class="responsive-img" alt="数据类型">
                        
                        <span class="card-title">数据类型</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            简单整理了些常用的数据类型，因为某些的具体会定总是记不住，所以就整理下。
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2021-08-21
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/%E8%AE%A1%E7%AE%97%E6%9C%BA%E5%8E%9F%E7%90%86/" class="post-category">
                                    计算机原理
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B/">
                        <span class="chip bg-color">数据类型</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>


<script>
    $('#articleContent').on('copy', function (e) {
        // IE8 or earlier browser is 'undefined'
        if (typeof window.getSelection === 'undefined') return;

        var selection = window.getSelection();
        // if the selection is short let's not annoy our users.
        if (('' + selection).length < Number.parseInt('120')) {
            return;
        }

        // create a div outside of the visible area and fill it with the selected text.
        var bodyElement = document.getElementsByTagName('body')[0];
        var newdiv = document.createElement('div');
        newdiv.style.position = 'absolute';
        newdiv.style.left = '-99999px';
        bodyElement.appendChild(newdiv);
        newdiv.appendChild(selection.getRangeAt(0).cloneContents());

        // we need a <pre> tag workaround.
        // otherwise the text inside "pre" loses all the line breaks!
        if (selection.getRangeAt(0).commonAncestorContainer.nodeName === 'PRE' || selection.getRangeAt(0).commonAncestorContainer.nodeName === 'CODE') {
            newdiv.innerHTML = "<pre>" + newdiv.innerHTML + "</pre>";
        }

        var url = document.location.href;
        newdiv.innerHTML += '<br />'
            + '来源: X-Y-Z`s Blog<br />'
            + '文章作者: Zhang-little-white<br />'
            + '文章链接: <a href="' + url + '">' + url + '</a><br />'
            + '本文章著作权归作者所有，任何形式的转载都请注明出处。';

        selection.selectAllChildren(newdiv);
        window.setTimeout(function () {bodyElement.removeChild(newdiv);}, 200);
    });
</script>


<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget card">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('2'),
            headingSelector: 'h1,h2, h3, h4, h5'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h1,h2, h3, h4, h5').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>




    <footer class="page-footer bg-color">
    

    <div class="container row center-align"
         style="margin-bottom: 15px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            
                <span id="year">2021-2022</span>
            
            <span id="year">2021</span>
            <a href="/about" target="_blank">Zhang-little-white</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
                &nbsp;<i class="fas fa-chart-area"></i>&nbsp;站点总字数:&nbsp;<span
                        class="white-color">53.2k</span>
            
            
            
            
            
            <br>

            <!-- 运行天数提醒. -->
            
                <span id="sitetime"> Loading ...</span>
                <script>
                    var calcSiteTime = function () {
                        var seconds = 1000;
                        var minutes = seconds * 60;
                        var hours = minutes * 60;
                        var days = hours * 24;
                        var years = days * 365;
                        var today = new Date();
                        var startYear = "2021";
                        var startMonth = "8";
                        var startDate = "12";
                        var startHour = "0";
                        var startMinute = "0";
                        var startSecond = "0";
                        var todayYear = today.getFullYear();
                        var todayMonth = today.getMonth() + 1;
                        var todayDate = today.getDate();
                        var todayHour = today.getHours();
                        var todayMinute = today.getMinutes();
                        var todaySecond = today.getSeconds();
                        var t1 = Date.UTC(startYear, startMonth, startDate, startHour, startMinute, startSecond);
                        var t2 = Date.UTC(todayYear, todayMonth, todayDate, todayHour, todayMinute, todaySecond);
                        var diff = t2 - t1;
                        var diffYears = Math.floor(diff / years);
                        var diffDays = Math.floor((diff / days) - diffYears * 365);

                        // 区分是否有年份.
                        var language = 'zh-CN';
                        if (startYear === String(todayYear)) {
                            document.getElementById("year").innerHTML = todayYear;
                            var daysTip = 'This site has been running for ' + diffDays + ' days';
                            if (language === 'zh-CN') {
                                daysTip = '本站已运行 ' + diffDays + ' 天';
                            } else if (language === 'zh-HK') {
                                daysTip = '本站已運行 ' + diffDays + ' 天';
                            }
                            document.getElementById("sitetime").innerHTML = daysTip;
                        } else {
                            document.getElementById("year").innerHTML = startYear + " - " + todayYear;
                            var yearsAndDaysTip = 'This site has been running for ' + diffYears + ' years and '
                                + diffDays + ' days';
                            if (language === 'zh-CN') {
                                yearsAndDaysTip = '本站已运行 ' + diffYears + ' 年 ' + diffDays + ' 天';
                            } else if (language === 'zh-HK') {
                                yearsAndDaysTip = '本站已運行 ' + diffYears + ' 年 ' + diffDays + ' 天';
                            }
                            document.getElementById("sitetime").innerHTML = yearsAndDaysTip;
                        }
                    }
                    calcSiteTime();
                </script>
            
            <br>
            
                <span id="icp">
				<img src="/medias/icp.png"豫ICP备2021025736号
                                    style="vertical-align: text-bottom;"/>
                <a href="https://beian.miit.gov.cn" target="_blank">豫ICP备2021025736号</a>
            </span>
            
        </div>
        <div class="col s12 m4 l4 social-link ">
    <a href="https://github.com/xiaohuixian" class="tooltipped" target="_blank" data-tooltip="visit my GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:1970476603@qq.com" class="tooltipped" target="_blank" data-tooltip="邮件联系" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>







    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=1970476603" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 1970476603" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>







    <a href="/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>

</div>
    </div>
				
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script type="text/javascript">
$(function () {
    var searchFunc = function (path, search_id, content_id) {
        'use strict';
        $.ajax({
            url: path,
            dataType: "xml",
            success: function (xmlResponse) {
                // get the contents from search data
                var datas = $("entry", xmlResponse).map(function () {
                    return {
                        title: $("title", this).text(),
                        content: $("content", this).text(),
                        url: $("url", this).text()
                    };
                }).get();
                var $input = document.getElementById(search_id);
                var $resultContent = document.getElementById(content_id);
                $input.addEventListener('input', function () {
                    var str = '<ul class=\"search-result-list\">';
                    var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                    $resultContent.innerHTML = "";
                    if (this.value.trim().length <= 0) {
                        return;
                    }
                    // perform local searching
                    datas.forEach(function (data) {
                        var isMatch = true;
                        var data_title = data.title.trim().toLowerCase();
                        var data_content = data.content.trim().replace(/<[^>]+>/g, "").toLowerCase();
                        var data_url = data.url;
                        data_url = data_url.indexOf('/') === 0 ? data.url : '/' + data_url;
                        var index_title = -1;
                        var index_content = -1;
                        var first_occur = -1;
                        // only match artiles with not empty titles and contents
                        if (data_title !== '' && data_content !== '') {
                            keywords.forEach(function (keyword, i) {
                                index_title = data_title.indexOf(keyword);
                                index_content = data_content.indexOf(keyword);
                                if (index_title < 0 && index_content < 0) {
                                    isMatch = false;
                                } else {
                                    if (index_content < 0) {
                                        index_content = 0;
                                    }
                                    if (i === 0) {
                                        first_occur = index_content;
                                    }
                                }
                            });
                        }
                        // show search results
                        if (isMatch) {
                            str += "<li><a href='" + data_url + "' class='search-result-title'>" + data_title + "</a>";
                            var content = data.content.trim().replace(/<[^>]+>/g, "");
                            if (first_occur >= 0) {
                                // cut out 100 characters
                                var start = first_occur - 20;
                                var end = first_occur + 80;
                                if (start < 0) {
                                    start = 0;
                                }
                                if (start === 0) {
                                    end = 100;
                                }
                                if (end > content.length) {
                                    end = content.length;
                                }
                                var match_content = content.substr(start, end);
                                // highlight all keywords
                                keywords.forEach(function (keyword) {
                                    var regS = new RegExp(keyword, "gi");
                                    match_content = match_content.replace(regS, "<em class=\"search-keyword\">" + keyword + "</em>");
                                });

                                str += "<p class=\"search-result\">" + match_content + "...</p>"
                            }
                            str += "</li>";
                        }
                    });
                    str += "</ul>";
                    $resultContent.innerHTML = str;
                });
            }
        });
    };

    searchFunc('/search.xml', 'searchInput', 'searchResult');
});
</script>

    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>
<div>
<a onclick="switchNightMode()" id="sma" title="模式切换">
    <i class="fa fa-moon-o" id="nightMode" aria-hidden="true"></i>
</a>
</div>


    <script src="/libs/materialize/materialize.min.js"></script>
    <script src="/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/libs/aos/aos.js"></script>
    <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/js/matery.js"></script>
    <script src="/libs/mermaid/mermaid.min.js"></script>

    <!-- Baidu Analytics -->

<script>
    var _hmt = _hmt || [];
    (function () {
        var hm = document.createElement("script");
        hm.src = "https://hm.baidu.com/hm.js?b3593488200a34a873defcaa11fc888a";
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(hm, s);
    })();
</script>

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/libs/others/clicklove.js" async="async"></script>
    
    

    

    

    <!--腾讯兔小巢-->
    
        <div style="position:fixed;bottom:125px;right:16px;cursor: pointer;" ID="tuxiaochao">
            <a title="兔小巢" target="_blank" rel="noopener" href="https://support.qq.com/products/348756"><i class="fa fa-comments fa-3x"  aria-hidden="true"></i></a>
        </div>
    
    

    
    
    <script type="text/javascript" size="150" alpha='0.6'
        zIndex="-1" src="/libs/background/ribbon-refresh.min.js" async="async"></script>
    

    
    <script type="text/javascript" src="/libs/background/ribbon-dynamic.js" async="async"></script>
    

    
    <script src="/libs/instantpage/instantpage.js" type="module"></script>
    
	<script type="text/javascript">
//	//只在桌面版网页启用特效
	//var windowWidth = $(window).width();
	//if (windowWidth > 768) {
//		document.write('<script type="text/javascript" src="/js/sakura.js"><\/script>');
//	}
	</script>
	
	<script type="text/javascript">
		var OriginTitile=document.title,st;
		document.addEventListener("visibilitychange",function(){ document.hidden?(document.title="ヽ(●-`Д´-)ノ110，有人失踪了",clearTimeout(st)):(document.title="(Ő∀Ő3)ノ失踪人口回归！",st=setTimeout(function(){document.title=OriginTitile},3e3))
		})
	</script>


</body>

</html>
